如何通过 java 类 ( servlet ) 验证 jsp 页面并根据结果向前或返回错误消息?
提前致谢。
doPost()
servlet中,接收数据如果验证正确,有条件地将请求转发到成功页面,或者在验证失败的情况下,在请求属性中设置错误消息并再次将请求转发到 FORM 页面
// Prepare messages.
Map<String, String> messages = new HashMap<String, String>();
request.setAttribute("messages", messages);
// Get and validate name.
String name = request.getParameter("name");
if (name == null || name.trim().isEmpty()) {
messages.put("name", "Please enter name");
} else if (!name.matches("\\p{Alnum}+")) {
messages.put("name", "Please enter alphanumeric characters only");
}
// Get and validate age.
String age = request.getParameter("age");
if (age == null || age.trim().isEmpty()) {
messages.put("age", "Please enter age");
} else if (!age.matches("\\d+")) {
messages.put("age", "Please enter digits only");
}
// No validation errors? Do the business job!
if (messages.isEmpty()) {
messages.put("success", String.format("Hello, your name is %s and your age is %s!", name, age));
}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);