How perform validation and display error message in same form in JSP?

How can I display an error message in the very same JSP when a user submits a wrong input? I do not intend to throw an exception and show an error page.


Solution 1:

Easiest would be to have placeholders for the validation error messages in your JSP.

The JSP /WEB-INF/foo.jsp:

<form action="${pageContext.request.contextPath}/foo" method="post">
    <label for="foo">Foo</label>
    <input id="foo" name="foo" value="${fn:escapeXml(param.foo)}">
    <span class="error">${messages.foo}</span>
    <br />
    <label for="bar">Bar</label>
    <input id="bar" name="bar" value="${fn:escapeXml(param.bar)}">
    <span class="error">${messages.bar}</span>
    <br />
    ...
    <input type="submit">
    <span class="success">${messages.success}</span>
</form>

In the servlet where you submit the form to, you can use a Map<String, String> to get hold of the messages which are to be displayed in JSP.

The Servlet @WebServlet("foo"):

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/WEB-INF/foo.jsp").forward(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map<String, String> messages = new HashMap<String, String>();
    request.setAttribute("messages", messages); // Now it's available by ${messages}

    String foo = request.getParameter("foo");
    if (foo == null || foo.trim().isEmpty()) {
        messages.put("foo", "Please enter foo");
    } else if (!foo.matches("\\p{Alnum}+")) {
        messages.put("foo", "Please enter alphanumeric characters only");
    }

    String bar = request.getParameter("bar");
    if (bar == null || bar.trim().isEmpty()) {
        messages.put("bar", "Please enter bar");
    } else if (!bar.matches("\\d+")) {
        messages.put("bar", "Please enter digits only");
    }

    // ...

    if (messages.isEmpty()) {
        messages.put("success", "Form successfully submitted!");
    }

    request.getRequestDispatcher("/WEB-INF/foo.jsp").forward(request, response);
}

In case you create more JSP pages and servlets doing less or more the same, and start to notice yourself that this is after all a lot of repeated boilerplate code, then consider using a MVC framework instead.

See also:

  • Our Servlets wiki page
  • What is the best practice for validating parameters in JSP?