Skip to main content
edited tags; edited title
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

Elegant way to handle errors with Servlet and JSP for user registration, with CAPTCHA and Servlets (Model 2)error handling

Source Link
k_rollo
  • 478
  • 5
  • 14

Elegant way to handle errors with JSP and Servlets (Model 2)

I have a form that submits to a registration Servlet, which inserts a new user to the database when they sign up to the web application. Depending on the erroneous user input, the Servlet will sendRedirect() to a result page, telling the user what went wrong.

Servlet: doPost()

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String userId = request.getParameter("username");
    String userEmail1 = request.getParameter("email1");
    String userEmail2 = request.getParameter("email2");
    String userPassword1 = request.getParameter("pass1");
    String userPassword2 = request.getParameter("pass2");
    String captchaAnswer = request.getParameter("answer");
    
    String[] userDetails = {
        userId,
        userEmail1,
        userEmail2,
        userPassword1,
        userPassword2,
        captchaAnswer,
    };
    
    UserManager um = new UserManager();
    boolean isElementNull = um.isElementNull(userDetails);
    
    if(isElementNull) {
        response.sendRedirect("index.jsp");
        return;
    }
    
    // simple captcha
    HttpSession session = request.getSession(true);
    Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);
    
    if(captcha == null) {
        response.sendRedirect("register.jsp");
        return;
    }
    
    request.setCharacterEncoding("UTF-8");  
            
    boolean isCaptchaCorrect = captcha.isCorrect(captchaAnswer);
    session.setAttribute("isCaptchaCorrect", isCaptchaCorrect);
    
    // for retaining form value
    session.setAttribute("userId", userId);
    session.setAttribute("userEmail1", userEmail1);
    session.setAttribute("userEmail2", userEmail2);
                
    if(isCaptchaCorrect) {
        // validate inputs
        boolean isUsernameBlank = um.isFieldBlank(userId);
        boolean isEmailBlank = um.isFieldBlank(userEmail1);
        boolean isPasswordBlank = um.isFieldBlank(userPassword1);
        boolean isEmailValid = um.isEmailValid(userEmail1, userEmail2);
        boolean isPasswordLengthValid = um.isPasswordLengthValid(userPassword1, userPassword2);         
        boolean isExistingUsername = um.isExisting("user_id", userId);
        boolean isExistingEmail = um.isExisting("user_email", userEmail1);
        boolean isEmailMatch = um.isMatch(userEmail1, userEmail2);
        boolean isPasswordMatch = um.isMatch(userPassword1, userPassword2);
                    
        // bind objects to session
        session.setAttribute("isUsernameBlank", isUsernameBlank);
        session.setAttribute("isEmailBlank", isEmailBlank);
        session.setAttribute("isPasswordBlank", isPasswordBlank);
        session.setAttribute("isEmailValid", isEmailValid);
        session.setAttribute("isPasswordLengthValid", isPasswordLengthValid);           
        session.setAttribute("isExistingUsername", isExistingUsername);
        session.setAttribute("isExistingEmail", isExistingEmail);
        session.setAttribute("isEmailMatch", isEmailMatch);
        session.setAttribute("isPasswordMatch", isPasswordMatch);       

        if(isUsernameBlank || isEmailBlank || isPasswordBlank || !isEmailValid || !isPasswordLengthValid
            || isExistingUsername || isExistingEmail || !isEmailMatch || !isPasswordMatch) {
            
            response.sendRedirect("register-result.jsp");
                    
        // register success
        } else {
            String userPassword = userPassword1;
            String userEmail = userEmail1;
            
            // get current system time
            java.util.Date utilDate = new java.util.Date();
            
            // convert to sql date
            java.sql.Date registeredDate = new java.sql.Date(utilDate.getTime());
            
            // assemble user bean object
            User user = UserAssembler.getInstance(
                userId,
                userPassword,
                userEmail,
                2, // 2 = User
                registeredDate
            );
            
            // insert user into database
            um.registerUser(user);  
            
            response.sendRedirect("register-result.jsp");
        }
    
    // wrong captcha answer
    } else {
        response.sendRedirect("register-result.jsp");               
    }
}

JSP: (register-result.jsp)

<body>
    <strong>REGISTER</strong>

    <%
    Boolean isCaptchaCorrect = (Boolean) session.getAttribute("isCaptchaCorrect");
    
    if(isCaptchaCorrect == null) {
        response.sendRedirect("index.jsp");
        return;
    }
    
    if(isCaptchaCorrect) {
        Boolean isUsernameBlank = (Boolean) session.getAttribute("isUsernameBlank");
        Boolean isEmailBlank = (Boolean) session.getAttribute("isEmailBlank");
        Boolean isPasswordBlank = (Boolean) session.getAttribute("isPasswordBlank");
        Boolean isEmailValid = (Boolean) session.getAttribute("isEmailValid");
        Boolean isPasswordLengthValid = (Boolean) session.getAttribute("isPasswordLengthValid");                
        Boolean isExistingUsername = (Boolean) session.getAttribute("isExistingUsername");
        Boolean isExistingEmail = (Boolean) session.getAttribute("isExistingEmail");
        Boolean isEmailMatch = (Boolean) session.getAttribute("isEmailMatch");
        Boolean isPasswordMatch = (Boolean) session.getAttribute("isPasswordMatch");
    
    if(isUsernameBlank) {
    %>

    <form action="register.jsp">
    <table>
        <tr><td style="color: #FF0000">Username cannot be blank!</td></tr>
    </table>
    <br/>
    <input type="submit" value="Try Again"/>
    </form>
    
    <% } else if(isEmailBlank) { %>
    
    <form action="register.jsp">
    <table>
        <tr><td style="color: #FF0000">Email cannot be blank!</td></tr>
    </table>
    <br/>
    <input type="submit" value="Try Again"/>
    </form>
    
    <% } else if(isPasswordBlank) { %>
    
    <form action="register.jsp">
    <table>
        <tr><td style="color: #FF0000">Password cannot be blank!</td></tr>
    </table>
    <br/>
    <input type="submit" value="Try Again"/>
    </form>
    
    <% } else if(!isEmailValid) { %>
    
    <form action="register.jsp">
    <table>
        <tr><td style="color: #FF0000">Email is not in a valid format!</td></tr>
    </table>
    <br/>
    <input type="submit" value="Try Again"/>
    </form>
    
    <% } else if(!isPasswordLengthValid) { %>
    
    <form action="register.jsp">
    <table>
        <tr><td style="color: #FF0000">Password must be at least 8 characters!</td></tr>
    </table>
    <br/>
    <input type="submit" value="Try Again"/>
    </form>
    
    <% } else if(isExistingUsername) { %>
    
    <form action="register.jsp">
    <table>
        <tr><td style="color: #FF0000">Username already exists!</td></tr>
    </table>
    <br/>
    <input type="submit" value="Try Again"/>
    </form>
    
    <% } else if(isExistingEmail) { %>
    
    <form action="register.jsp">
    <table>
        <tr><td style="color: #FF0000">Email already exists!</td></tr>
    </table>
    <br/>
    <input type="submit" value="Try Again"/>
    </form>
                    
    <% } else if(!isEmailMatch) { %>
    
    <form action="register.jsp">
    <table>
        <tr><td style="color: #FF0000">Emails entered do not match!</td></tr>
    </table>
    <br/>
    <input type="submit" value="Try Again"/>
    </form>
    
    <% } else if(!isPasswordMatch) { %>
    
    <form action="register.jsp">
    <table>
        <tr><td style="color: #FF0000">Passwords entered do not match!</td></tr>
    </table>
    <br/>
    <input type="submit" value="Try Again"/>
    </form>
    
    <% } else { %>
    
    <!-- register success -->
    <form action="login.jsp">
    <table>
        <tr><td>Your registration was successful!</td></tr>
    </table>
    <br/>
    <input type="submit" value="Login"/>
    </form>
    
    <% }
    
    } else { %>             
    
    <!-- wrong captcha answer -->
    <form action="register.jsp">
    <table>
        <tr><td style="color: #FF0000">Your CAPTCHA answer is incorrect!</td></tr>
    </table>
    <br/>
    <input type="submit" value="Try Again"/>
    </form>

    <% } %>
</body>

The code appears unwieldy with all the booleans being setAttribute() in the Servlet and then getAttribute() in the JSP. The error messages are also hardcoded in JSP as seen above.

Is there an elegant way to handle user input errors and error messages, where they do not have to be hardcoded in the JSP itself?

(Please bear with me as we are limited to using scriptlets for now.)