1

The following code does not insert a row into the corresponding table. I have already tested the db connection and ran the query in the database, both of which have passed however when I add inputs via a .jsp form the values are still not inserting.

public class UserDao {

public String registerUser(User user){
    String username = user.getUsername();
    String email = user.getEmail();
    String password = user.getPassword();

    Connection con;
    con = DBConnection.createConnection();

    PreparedStatement preparedStatement;

    try{
        con.setAutoCommit(false);

        String query = ("INSERT INTO user (username, email, password, user_id) VALUES(?, ?, ?, ?)");
        preparedStatement = con.prepareStatement(query);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, email);
        preparedStatement.setString(3, password);
        preparedStatement.setString(4,null);

        int i = preparedStatement.executeUpdate();
        con.commit();
        preparedStatement.close();
        con.close();

        if(i !=0 ){
            return "SUCCESS";
        }
    }catch(SQLException e){
      throw new RuntimeException(e);

    }

    return "Something is wrong!";
}

}

For reference here is what my servlet class and .jsp file looks also like:

public class UserRegistrationServlet extends HttpServlet {

public UserRegistrationServlet(){}
/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String userName = request.getParameter("username");
    String email = request.getParameter("email");
    String password = request.getParameter("password");
    User user = new User();
    user.setUsername(userName);
    user.setEmail(email);
    user.setPassword(password);
    UserDao userDao = new UserDao();
    String userRegistered = userDao.registerUser(user);
    if(userRegistered.equals("SUCCESS")){
        request.getRequestDispatcher("test.jsp").forward(request, response);

    }else{
        request.setAttribute("error", userRegistered);
        request.getRequestDispatcher("/UserRegistration.jsp").forward(request, response);
    }
}

}

    <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Register</title>
<script> 
function validate()
{ 
var username = document.form.username.value; 
var email = document.form.email.value;
var password = document.form.password.value;
var conpassword= document.form.conpassword.value;
if (username==null || username=="")
{ 
alert("Full Name can't be blank"); 
return false; 
}
else if (email==null || email=="")
{ 
alert("Email can't be blank"); 
return false; 
}
else if(password.length<6)
{ 
alert("Password must be at least 6 characters long."); 
return false; 
} 
else if (password!=conpassword)
{ 
alert("Confirm Password should match with the Password"); 
return false; 
} 
} 
</script> 
</head>
<body>
<center><h2>Java Registration application using MVC and MySQL </h2></center>
<form name="form" action="UserRegistrationServlet" method="post" onsubmit="return validate()">
<table align="center">
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" name="conpassword" /></td>
</tr>
<tr>
<td><%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register"></input><input
type="reset" value="Reset"></input></td>
</tr>
</table>
</form>
</body>
</html>

Not sure where the error in my code, so any advice will be very helpful. Thanks

Updates:

user table in MySQL

[![After throwing a runtime exception ][2]][2]

5
  • please update the table description in the question. Also, update with any error logs that you are seeing on the console? Commented Mar 11, 2019 at 21:36
  • Hi I have added the updates you have requested ( the 1st row was from when i previously tested if the query worked in the database). Also I am not seeing any error logs on the console. Commented Mar 11, 2019 at 22:01
  • In general it is not a good practice to catch exceptions and not do anything with them. Can you throw a new 'RuntimeException' instead of just printing the stack trace when you catch 'SQLException? This may not be your issue but I have see code exactly like this hiding obvious issues. Commented Mar 11, 2019 at 22:02
  • @CharlieWallace Hi I made the changes you have a requested and I see the error now. What changes would i need to make to the so that the id column auto increments ? Commented Mar 11, 2019 at 22:25
  • The error tells you that you are passing a null to a column configured to require a value. Your code says you are passing a null to that column, user_id. So what seems mysterious to you? Commented Mar 11, 2019 at 22:43

1 Answer 1

3

You're setting user_id to null and the database complains that the column must not be null. I assume that you haven't passed null to the statement you tested against the DB directly, so that you were setting an empty string instead (or the table is to set a default or automatically generated value in case it's missing).

If there is a default value or a autogenerated one, you can simply leave away user_id in your insert statement and it should work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.