当用户提交错误输入时,我该如何在同一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>
Map<String,String>
来获取要在JSP中显示的消息。@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框架。
我不太确定你所说的“显示错误消息”是什么意思。如果您有标准的错误处理,那么您总是可以检查选项:
<%
if(wrong option selected)
throw new Exception("Invalid option selected");
%>