Spring MVC - 错误处理示例



以下示例展示了如何在Spring Web MVC框架中使用错误处理和验证器处理表单。首先,我们需要一个可用的Eclipse IDE,并按照以下步骤开发一个基于Spring Web框架的动态表单Web应用程序。

步骤 描述
1 创建一个名为HelloWeb的项目,包名为com.tutorialspoint,具体步骤请参考Spring MVC - HelloWorld章节。
2 在com.tutorialspoint包下创建Java类Student,StudentController和StudentValidator。
3 在jsp子文件夹下创建视图文件addStudent.jsp和result.jsp。
4 最后一步是创建源代码和配置文件的内容,并导出应用程序,具体说明如下。

Student.java

package com.tutorialspoint;

public class Student {
   private Integer age;
   private String name;
   private Integer id;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }

   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }

   public void setId(Integer id) {
      this.id = id;
   }
   public Integer getId() {
      return id;
   }
}

StudentValidator.java

package com.tutorialspoint;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class StudentValidator implements Validator {

   @Override
   public boolean supports(Class<?> clazz) {
      return Student.class.isAssignableFrom(clazz);
   }

   @Override
   public void validate(Object target, Errors errors) {		
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, 
         "name", "required.name","Field name is required.");
   }
}

StudentController.java

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentController {

   @Autowired
   @Qualifier("studentValidator")
   private Validator validator;

   @InitBinder
   private void initBinder(WebDataBinder binder) {
      binder.setValidator(validator);
   }

   @RequestMapping(value = "/addStudent", method = RequestMethod.GET)
   public ModelAndView student() {
      return new ModelAndView("addStudent", "command", new Student());
   }

   @ModelAttribute("student")
   public Student createStudentModel() {	
      return new Student();
   }

   @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
   public String addStudent(@ModelAttribute("student") @Validated Student student, 
      BindingResult bindingResult, Model model) {

      if (bindingResult.hasErrors()) {
         return "addStudent";
      }
      model.addAttribute("name", student.getName());
      model.addAttribute("age", student.getAge());
      model.addAttribute("id", student.getId());

      return "result";
   }
}

HelloWeb-servlet.xml

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:context = "http://www.springframework.org/schema/context"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package = "com.tutorialspoint" />

   <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name = "prefix" value = "/WEB-INF/jsp/" />
      <property name = "suffix" value = ".jsp" />
   </bean>
 
   <bean id = "studentValidator" class = "com.tutorialspoint.StudentValidator" />
</beans>

这里,对于第一个服务方法**student()**,我们在ModelAndView对象中传递了一个空的Student对象,名称为“command”,因为如果您在JSP文件中使用<form:form>标签,Spring框架期望一个名为“command”的对象。因此,当调用student()方法时,它会返回**addStudent.jsp**视图。

第二个服务方法**addStudent()**将针对**HelloWeb/addStudent** URL上的POST方法调用。您将根据提交的信息准备模型对象。最后,服务方法将返回“result”视图,这将导致渲染result.jsp。如果使用验证器生成错误,则返回相同的视图“addStudent”,Spring会自动将错误消息从**BindingResult**注入视图中。

addStudent.jsp

<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
   <head>
      <title>Spring MVC Form Handling</title>
   </head>
   <style>
      .error {
         color: #ff0000;
      }

      .errorblock {
         color: #000;
         background-color: #ffEEEE;
         border: 3px solid #ff0000;
         padding: 8px;
         margin: 16px;
      }
   </style>
   
   <body>
      <h2>Student Information</h2>
      <form:form method = "POST" action = "/HelloWeb/addStudent" commandName = "student">
      <form:errors path = "*" cssClass = "errorblock" element = "div" />
         <table>
            <tr>
               <td><form:label path = "name">Name</form:label></td>
               <td><form:input path = "name" /></td>
               <td><form:errors path = "name" cssClass = "error" /></td>
            </tr>
            <tr>
               <td><form:label path = "age">Age</form:label></td>
               <td><form:input path = "age" /></td>
            </tr>
            <tr>
               <td><form:label path = "id">id</form:label></td>
               <td><form:input path = "id" /></td>
            </tr>
            <tr>
               <td colspan = "2">
               <input type = "submit" value = "Submit"/>
               </td>
            </tr>
         </table>  
      </form:form>
   </body>
</html>

这里我们使用**<form:errors />**标签,path="*"属性来渲染错误消息。例如

<form:errors path = "*" cssClass = "errorblock" element = "div" />

它将渲染所有输入验证的错误消息。

我们使用**<form:errors />**标签,path="name"属性来渲染name字段的错误消息。例如

<form:errors path = "name" cssClass = "error" />

它将渲染name字段验证的错误消息。

result.jsp

<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
   <head>
      <title>Spring MVC Form Handling</title>
   </head>
   <body>

      <h2>Submitted Student Information</h2>
      <table>
         <tr>
            <td>Name</td>
            <td>${name}</td>
         </tr>
         <tr>
            <td>Age</td>
            <td>${age}</td>
         </tr>
         <tr>
           <td>ID</td>
           <td>${id}</td>
         </tr>
      </table>  
   </body>
</html>

创建完源代码和配置文件后,导出应用程序。右键单击应用程序,使用**导出→WAR文件**选项,并将**HelloWeb.war**文件保存到Tomcat的webapps文件夹中。

现在,启动Tomcat服务器,并确保您可以使用标准浏览器访问webapps文件夹中的其他网页。尝试URL - **https://127.0.0.1:8080/HelloWeb/addStudent**,如果Spring Web应用程序一切正常,您将看到以下屏幕。

Spring Validation

提交所需信息后,单击提交按钮提交表单。如果Spring Web应用程序一切正常,您将看到以下屏幕。

Spring Validation Result
广告