为什么会有Postgres例外?

时间:2013-10-23 10:18:37

标签: java postgresql tomcat servlets jdbc

下午好。我尝试从eclipse的java代码连接到数据库。我需要提出请求并检查表单中输入的用户名和密码是否相互匹配。用户名及其密码列表位于名为stud_test的数据库中。我需要运行gradle和tomcat才能检查servlet是否正常工作。当我这样做并打开所需页面时,我会看到PSQLExceptions。我的代码示例如下。我无法理解这是什么问题。

public void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException,IOException {

    Connection con;
    ResultSet rs;

    String URL = "jdbc:postgresql://localhost:5432/stud_test";
    String username = request.getParameter("useruser");
    String passwrd = request.getParameter("pass");
    response.setContentType("text/html");

    try {
        con = DriverManager.getConnection(URL, "postgres", "postgres");
        Statement st = con.createStatement();
        st.executeQuery ("SELECT password FROM stud WHERE user = " + username);
        rs = st.getResultSet();

        if (passwrd.equals(rs)){
            request.getServletContext().getRequestDispatcher(
            "/jsp/hello.jsp").forward(request, response);
        }
        else {
            request.getServletContext().getRequestDispatcher("/jsp/fail.jsp").forward(request, response);
        }

        rs.close ();
        st.close ();
    } 

    catch(Exception e) {
        System.out.println("Exception is :" + e);
    }   
}

2 个答案:

答案 0 :(得分:1)

除了Sergiu已经提到过的内容之外,以下几行不太可能达到你想要的效果:

st.executeQuery ("SELECT password FROM stud WHERE user = " + username);

例如,如果用户名是“carl”,那么以下语句将被发送到数据库:

SELECT password FROM stud WHERE user = carl

,如果没有名为“carl”的列,则会导致语法错误。解决这个问题的“明显的”(和错误的方法!)将是使用

st.executeQuery ("SELECT password FROM stud WHERE user = '" + username + "'");

这可能会起作用(起初),但是您容易受到SQL注入的攻击。请求信息的正确方法是使用prepared statements和参数:

final PreparedStatement stm = connection.prepareStatement(
        "SELECT password FROM stud WHERE user = ?");

try {

    // For each "hole" ("?" symbol) in the SQL statement, you have to provide a
    // value before the query can be executed. The holes are numbered from left to
    // right, starting with the left-most one being 1. There are a lot of "setXxx"
    // methods in the prepared statement interface, and which one you need to use
    // depends on the type of the actual parameter value. In this case, we assign a
    // string parameter:

    stm.setString(1, username);

    final ResultSet rs = stm.executeQuery();

    try {

        if (rs.next()) {

            if (password.equals(rs.getString(1))) {

                 // Yay. Passwords match. User may log in

            }
        }

    } finally {

         rs.close();
    }

} finally {

    stm.close();
}

是的,在Java中通过JDBC与数据库交谈需要大量的样板代码。不,“明显”的解决方案是错误的!错误!错了!

答案 1 :(得分:0)

我认为你应该

if (passwrd.equals(rs.getString(1))){ ... }

假设用户字段是数据库中的varchar。

您无法将字符串(passwrd)与ResultSet实例(rs)匹配。