如何在JSP中以相同的形式执行验证和显示错误消息?
当用户提交错误的输入时,如何在同一个JSP中显示错误消息?我不打算抛出异常并显示错误页面。我不太清楚您所说的“显示错误消息”是什么意思。如果您有标准错误处理,则始终可以检查选项:如何在JSP中以相同的形式执行验证和显示错误消息?,jsp,validation,Jsp,Validation,当用户提交错误的输入时,如何在同一个JSP中显示错误消息?我不打算抛出异常并显示错误页面。我不太清楚您所说的“显示错误消息”是什么意思。如果您有标准错误处理,则始终可以检查选项: <% if(wrong option selected) throw new Exception("Invalid option selected"); %> 当然,这只是一个概念;最好您有自己的异常类。不过,我也不太确定您要的是什么。我看到了标签“表单验证”,所以也许您应该只
<%
if(wrong option selected)
throw new Exception("Invalid option selected");
%>
当然,这只是一个概念;最好您有自己的异常类。不过,我也不太确定您要的是什么。我看到了标签“表单验证”,所以也许您应该只使用JavaScript和客户端表单验证?如果需要使用JSP进行验证,请处理表单数据,并使用错误消息重新显示表单或接受表单数据(如果正确)。最简单的方法是在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>
如果你创建更多的JSP页面和servlet做得更少或更多,并且开始注意到这毕竟是大量重复的样板代码,那么考虑使用MVC框架。
另见:
@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);
}