Checking for duplicate usernames in Database
I have this Servlet code, I am trying to check for duplicate usernames in the database but it does not seem to work out.
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 != user开发者_如何学运维name) {
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();
}
}
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..:)");
}
The problem is the line duplicate = rs.getString(username);
. You meant to retrieve the value in the username column from the result set, but you're using the username
variable, not the string "username"
. When you enter "ankur" as the username, that line is equivalent to duplicate = rs.getString("ankur");
, and there's no column named ankur
in the result set.
You have a bunch of other bugs as well:
rs.next()
will only return true if the query found an existing user record with the specified username. That means you can only get to the successful registration code if there is a duplicate user.password.equals("confirmpassword")
means that the user has to actually type the word "confirmpassword" in the password box or their registration will be rejected. I think you meantpassword.equals(confirmpassword)
.- You're logging into your database as root and you have SQL injection vulnerabilities. A malicious user could do anything they want with your database, such as modifying or deleting your data.
- Why are you catching and ignoring
ClassNotFoundException
?
精彩评论