我有这个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();
}
}
答案 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)
。ClassNotFoundException
?