目录
JSR 303 是 Java 为 Bean 数据合法性校验提供的标准框架,它已经包含在 JavaEE 中。我们可以通过注解的方式来指定属性值的范围。
上面的注解为JSR303提供的基本注解,下面的为Hibernate Validator提供的注解
先创建一个JavaBean
- public class Student {
- private Integer id;
- @Length(max = 5)
- private String name;
- @Min(12)
- private Integer age;
- @DateTimeFormat(pattern = "yy-MM-dd")
- //我在get方法中返回的是格式化后的字符串
- private Date birthday;
- @NumberFormat(pattern = "yyyy-MM-dd")
- @org.hibernate.validator.constraints.Email
- private String Email;
-
- public Student() {
- }
-
- @Override
- public String toString() {
- return "Student{" +
- "id=" + id +
- ", name='" + name + '\'' +
- ", age=" + age +
- ", birthday=" + birthday +
- ", Email='" + Email + '\'' +
- '}';
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- 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;
- }
-
- public String getBirthday() {
- if (this.birthday == null)return "";
- return new SimpleDateFormat("yyyy-MM-dd").format(this.birthday);
- }
-
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
-
- public String getEmail() {
- return Email;
- }
-
- public void setEmail(String email) {
- Email = email;
- }
-
- public Student(Integer id, String name, Integer age, Date birthday, String email) {
- this.id = id;
- this.name = name;
- this.age = age;
- this.birthday = birthday;
- Email = email;
- }
- }
创建handler
- @RequestMapping("/f3")
- public String f3(@Valid @RequestBody Student student) {
- System.out.println(student);
- System.out.println("---------------\n\n");
- return "success";
- }
使用postman发送请求
数据不准确会抛出异常,当然,我们也可以获取异常的信息
我们在参数列表写上该参数,springmvc会将封装错误信息的校验结果进行传入
- @RequestMapping("/f3")
- public String f3(@Valid @RequestBody Student student, BindingResult bindingResult) {
- for (ObjectError error : bindingResult.getAllErrors()) {
- System.out.println(error);
- }
- System.out.println(student);
- System.out.println("---------------\n\n");
- return "success";
- }
bindingResult会封装错误信息
通过注解的message来进行指定
springmvc会自动进行属性绑定,当然,我们也可以设置,让其不进行绑定,使用@InitBinder
- @InitBinder
- public void initBinder(WebDataBinder webDataBinder){
- webDataBinder.setDisallowedFields("name");
- }
@InitBinder标识在方法上面,该方法返回值为viod,参数为WebDataBinder,我们通过该参数来对某些属性进行解绑,上面代码,在本类里面的handler就不会接受到name
这些校验个人感觉用的不多了,了解即可