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

前端 未结 3 776
广开言路
广开言路 2020-11-22 15:43

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.

3条回答
  •  旧巷少年郎
    2020-11-22 16:06

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

    The JSP /WEB-INF/foo.jsp:

    ${messages.foo}
    ${messages.bar}
    ... ${messages.success}

    In the servlet where you submit the form to, you can use a Map 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 messages = new HashMap();
        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?

提交回复
热议问题