检查数据库中的重复用户名

时间:2011-10-04 04:37:28

标签: servlets

我有这个Servlet代码,我试图在数据库中检查重复的用户名,但似乎没有用。

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String confirmpassword = request.getParameter("confirm_password");

    try {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/account";
        Connection conn = DriverManager.getConnection(url, "root", "school");

        Statement statement = (Statement) conn.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * from Users where username='" + username + "';");

        String duplicate;

        while (rs.next()) {
            duplicate = rs.getString(username);

            if (password.equals("confirmpassword") && duplicate != username) {
                statement.executeUpdate("INSERT INTO info values('" + username + "','" + password + "');");
                out.println("Registraion Successful!");
                out.println("Your Username: "+username);
                out.println("Your Password: "+password);

            }
            if (duplicate.equals(username)){
                out.println("Please choose a different username..:)");
            }
        }




    } catch (SQLException ex) {
        Logger.getLogger(RegistrationServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
    } finally {
        out.close();
    }
}

2 个答案:

答案 0 :(得分:3)

Statement statement = (Statement) conn.createStatement();

ResultSet rs = statement.executeQuery("SELECT * from Users where username='" + username + "'");

String duplicate = null;

while(rs.next()){
duplicate = rs.getString(1);
}

if(duplicate == null){
// ur logic
}
else{
out.println("Please choose a different username..:)");
}

答案 1 :(得分:0)

问题是行duplicate = rs.getString(username);。您打算从结果集中检索用户名列中的值,但您使用的是username 变量,而不是字符串"username"。当您输入“ankur”作为用户名时,该行等同于duplicate = rs.getString("ankur");,并且结果集中没有名为ankur的列。

你还有其他一些错误:

    如果查询找到具有指定用户名的现有用户记录,
  • rs.next()将仅返回true。这意味着如果 是重复用户,您只能获得成功的注册码。
  • password.equals("confirmpassword")表示用户必须在密码框中实际输入“确认密码”一词,否则他们的注册将被拒绝。我认为你的意思是password.equals(confirmpassword)
  • 您以root身份登录数据库,并且存在SQL injection个漏洞。恶意用户可以对数据库执行任何操作,例如修改或删除数据。
  • 你为什么要抓住并忽略ClassNotFoundException