0

If there are error in jsp form and we want to display proper error message on jsp page then where should we handle that error in jsp page or in servlet

Sumeet
  • 87
  • 1
  • 10

1 Answers1

0

Definitely not in a jsp

Preferably in a servlet

Ideally in a helper class called by the Servlet

I'll try to sketch a brief example:

inside the Servlet class

// within the doPost method
String email = request.getParameter("email");
String password = request.getParameter("password");

FormValidator fm = new FormValidator();
fm.validateLogin(email, password);

// the errors attribute will contain a HashMap (returned by 
// the getter method) containing error String literals 
request.setAttribute("errors", fm.getInlineErrors());

request.getRequestDispatcher("formpage.jsp").forward(request,response);

inside the FormValidator class (the helper class)

private HashMap<String, String> errors = new Hashmap<String, String>();

// set empty inline errors in the constructor
public FormValidator(){
    errors.put("emailError", "");
    errors.put("passwordError", "");
    // add other errors for register form...
}

public HashMap<String, String> getInlineErrors(){
    return errors;
}

public void validateLogin(String email, String password){
    // put your validation code here
    // set inline errors accordingly
}

// create validateRegister() method

on the Jsp

<form action="Servlet" method="post">
    <input type="text" name = "email" value="${email}"/> ${errors['emailError']}
    <input type="text" name = "password" value="${password}"/> ${errors['passwordError']}
    <input type="submit" value="Log in"/>
</form>

Note:

  1. you don't have to use a HashMap for your errors, you can just use an arraylist or an array...I just prefer a HashMap so to have access to the fields with a String key rather than a numeric index to avoid "magic numbers" on the Jsp page

  2. you would probably use inline errors for a register form rather than a login, but a login form was quicker to implement here

  3. I did not put any HTML label, you may want to add them

While this approach does not provide a great scale of reuse across a single application as you would typically have no more than 2 forms (register and login) on your web app, it would allow to encapsulate the form validation logic in its own class making the servlet more lightweight: the servlet would mainly be responsible for routing the traffic in your application.

Angelo Oparah
  • 673
  • 1
  • 7
  • 18