继承spring的validator接口,实现对数据的校验
在org.springframework.validation这个包中提供了一些对数据校验的方法,其中Validator接口是其中的一个。
现在用Validator接口,完成对数据的校验.
第一步:先定义一个domain对象:Person:
Person的代码如下:
package com.validation; public class Person { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
第二步定义PersonValidator类,这个类继承了Validator这个类:
package com.validation; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class PersonValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Person.class.equals(clazz); } @Override public void validate(Object obj, Errors e) { ValidationUtils.rejectIfEmpty(e, "name", "name.empty"); Person p = (Person) obj; if (p.getAge() < 0) { e.rejectValue("age", "negativevalue"); } else if (p.getAge() > 110) { e.rejectValue("age", "too.darn.old"); } } }
第三步:controller层的代码如下:
package com.validation; import com.entity.Bar; import com.entity.BarValidator; import com.entity.Foo; import org.springframework.beans.PropertyValues; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.DataBinder; import org.springframework.validation.ObjectError; 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.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; @RestController public class FooController { @RequestMapping("/peopleTest") public String people(Person person){ PersonValidator validator = new PersonValidator(); if(validator.supports(Person.class)){ BindException errors = new BindException(person, "person"); validator.validate(person,errors); List<ObjectError> allErrors = errors.getAllErrors(); System.out.println("size="+allErrors.size()); for (int i=0;i<allErrors.size();i++) { System.out.println(allErrors.get(i).getCode()); } } return "success"; } }
第四步:springboot的启动类的代码如下:
package com.validation; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
第五步:在浏览器的地址栏中输入:http://localhost:8080/peopleTest?age=200 注意这里的age如果不写的话,会报NullPointException.如你只写为:http://localhost:8080/peopleTest
输出结果为:
size=2
name.empty
too.darn.old