最简单的方法是在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>
Run Code Online (Sandbox Code Playgroud)
在您提交表单的servlet中,您可以使用a Map<String, String>来获取要在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);
}
Run Code Online (Sandbox Code Playgroud)
如果您创建更多的JSP页面和servlet执行更少或更多相同的操作,并开始注意到这毕竟是很多重复的样板代码,那么请考虑使用MVC框架.
Ale*_*s G -2
我不太清楚“显示错误消息”是什么意思。如果您有标准的错误处理,那么您可以随时检查选项:
<%
if(wrong option selected)
throw new Exception("Invalid option selected");
%>
Run Code Online (Sandbox Code Playgroud)
当然,这只是一个想法;最好,您有自己的异常类。但话又说回来,我不太确定你在追求什么。