如何在 JSP 中以相同的形式执行验证和显示错误消息? [英] How perform validation and display error message in same form in JSP?

查看:27
本文介绍了如何在 JSP 中以相同的形式执行验证和显示错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户提交错误输入时,如何在同一个 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.

推荐答案

最简单的方法是在 JSP 中为验证错误消息设置占位符.

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

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>

在您提交表单的servlet中,您可以使用Map 获取要在 JSP 中显示的消息.

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.

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);
}

如果您创建了更多的 JSP 页面和 servlet,做的事情或多或少,并开始注意到这毕竟是大量重复的样板代码,那么请考虑改用 MVC 框架.

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.

这篇关于如何在 JSP 中以相同的形式执行验证和显示错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆