如何在JSP中执行验证并以相同的形式显示错误消息?

发布于 2024-10-12 13:34:06 字数 54 浏览 1 评论 0原文

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

话少心凉 2024-10-19 13:34:06

最简单的方法是在 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 中显示的消息。

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 框架。

另请参阅:

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:

趴在窗边数星星i 2024-10-19 13:34:06

我看到标签“form-validation”,所以也许您应该只使用 JavaScript 和客户端表单验证?如果您需要使用 JSP 进行验证,请处理表单数据,并重新显示带有错误消息的表单,或者接受表单数据(如果正确)。

I see tag "form-validation", so maybe you should just use JavaScript and client form validation? If you need validation with JSP, handle form data, and redisplay the form with an error message or accept form data, if it's correct.

空气里的味道 2024-10-19 13:34:06

我不太清楚“显示错误消息”是什么意思。如果您有标准的错误处理,那么您可以随时检查选项:

<%
    if(wrong option selected)
        throw new Exception("Invalid option selected");
%>

当然,这只是概念;最好,您有自己的异常类。但话又说回来,我不太确定你在追求什么。

I'm not quite sure what you mean by "display error message". If you have a standard error handling, then you can always check for options:

<%
    if(wrong option selected)
        throw new Exception("Invalid option selected");
%>

Of course, this is just the notion; preferably, you'd have your own exception class. But then again, I'm not quite sure what you're after.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文