Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...