我为输入做了一个html文本框,并希望将其连接到数据库。
但是每次我输入文本框并转到结果页面时,结果仅显示属性名称,而不显示任何元组。
我认为request.getParameter()返回null或空字符串。我做了几次尝试,但找不到任何解决方案。

这是我的代码。
这是selectTestForm.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.sql.*" %>

<!DOCTYPE html>
<html>
<head>
    <title>Select the game</title>
</head>
<body>
    <p>Input opponent team</p>
    <form name="form1" method="get" action="result.jsp">
        <p>Opponent team : <input type="text" name="oppon"></p>
        <p><input type="submit" name="Submit" value="send"></p>
    </form>
</body>
</html>


这就是result.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.sql.*" %>

<!DOCTYPE html>
<html>
<head>
    <title>Find the game</title>
</head>
<body>
    <table width="500" border="1">
        <tr>
            <td width="100">Game ID</td>
            <td width="100">Opponent Team</td>
            <td width="100">Start Date</td>
        </tr>
<%
    String opponent = (String) request.getParameter("oppon");

    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try{
        Class.forName("oracle.jdbc.driver.OracleDriver");
    }catch(ClassNotFoundException cnfe){
        cnfe.printStackTrace();
        System.out.println("Driver loading error");
    }
    try{
        String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:xe";
        String userId = "sports_booking";
        String userPass = "jade";
        con = DriverManager.getConnection(jdbcUrl, userId, userPass);

        String sql = "select * from game where opponent=?";

        pstmt = con.prepareStatement(sql);
        pstmt.setString(1, "opponent");
        rs = pstmt.executeQuery();

        while( rs.next() ) {
            String game_id = rs.getString("game_id");
            String start_date = rs.getString("start_date");

%>
            <tr>
                <td width="100"><%= game_id %></td>
                <td width="100"><%= opponent %></td>
                <td width="100"><%= start_date %></td>
            </tr>

<%
        }

    }catch(SQLException e){
        e.printStackTrace();

        if(rs != null) {
            try {
                rs.close();
            }catch(SQLException sqle) {}
        }
        if(pstmt != null) {
            try {
                pstmt.close();
            }catch(SQLException sqle) {}
        }
        if(con != null) {
            try {
                con.close();
            }catch(SQLException sqle) {}
        }
    }
%>

    </table>

</body>
</html>


如果您能帮助解决我的问题,我将不胜感激!

最佳答案

问题是行pstmt.setString(1, "opponent");,因为您设置了const "opponent"字符串而不是变量。

pstmt.setString(1, "opponent");-> pstmt.setString(1, opponent);现在应该可以使用。

10-06 10:05