0

如何通过 java 类 ( servlet ) 验证 jsp 页面并根据结果向前或返回错误消息?

提前致谢。

4

1 回答 1

2
  • 将表单从 jsp 发布到 setvlet
  • 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);

查看详细信息

于 2012-07-18T08:59:31.707 回答