Springboot进行hibernate-vidator数据验证

1、在进行Web项目开发的过程中,用户提交数据的合法性是最基础的验证手段,在SpringBoot中可以直接使用hibernate-vidator组件包实现验证处理,而此组件包中支持的验证注解,如图所示。


2、在src/main/resources目录下创建ValidationMessages.properties(文件名称为默认设置,不可更改)文件,该文件中要保留所有的错误提示信息。

1 userinfo.username.notnull.error=用户账号不能为空!
2 userinfo.email.from.error=请输入正确格式的用户邮箱!
3 userinfo.username.length.error=用户账号长度错误!
4 userinfo.age.notnull.error=用户年龄不能为空!
5 userinfo.age.digits.error=用户年龄必须是合法的数字!
6 userinfo.salary.notnull.error=用户工资不能为空!
7 userinfo.salary.digits.error=用户工资必须是合法的数字!
8 userinfo.birthday.notnull.error=用户生日不允许为空!

建立一个UserInfo实体类,并且在该类上使用验证注解。同时,验证出错时的错误信息引用之前ValidationMessages.properties文件中的定义。

 1 package com.demo.po;
 2 
 3 import java.io.Serializable;
 4 import java.util.Date;
 5 
 6 import javax.validation.constraints.Digits;
 7 import javax.validation.constraints.Email;
 8 import javax.validation.constraints.NotNull;
 9 
10 /**
11  * 
12  * @author
13  *
14  */
15 public class UserInfo implements Serializable {
16 
17     /**
18      * 
19      */
20     private static final long serialVersionUID = 1L;
21 
22     @NotNull(message = "{userinfo.username.notnull.error}")
23     private String userName;
24 
25     @Email(message = "{userinfo.email.from.error}")
26     private String email;
27 
28     @NotNull(message = "{userinfo.age.notnull.error}")
29     @Digits(integer = 3, fraction = 0, message = "{userinfo.age.digits.error}")
30     private Integer age;
31 
32     @NotNull(message = "{userinfo.salary.notnull.error}")
33     @Digits(integer = 20, fraction = 2, message = "{userinfo.salary.digits.error}")
34     private Integer salary;
35 
36     @NotNull(message = "{userinfo.birthday.notnull.error}")
37     private Date birthday;
38 
39     public String getUserName() {
40         return userName;
41     }
42 
43     public void setUserName(String userName) {
44         this.userName = userName;
45     }
46 
47     public String getEmail() {
48         return email;
49     }
50 
51     public void setEmail(String email) {
52         this.email = email;
53     }
54 
55     public Integer getAge() {
56         return age;
57     }
58 
59     public void setAge(Integer age) {
60         this.age = age;
61     }
62 
63     public Integer getSalary() {
64         return salary;
65     }
66 
67     public void setSalary(Integer salary) {
68         this.salary = salary;
69     }
70 
71     public Date getBirthday() {
72         return birthday;
73     }
74 
75     public void setBirthday(Date birthday) {
76         this.birthday = birthday;
77     }
78 
79 }

搞一个控制器,开始对字段进行校验判断,如下所示:

 1 package com.demo.controller;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.Iterator;
 5 
 6 import javax.validation.Valid;
 7 
 8 import org.springframework.beans.propertyeditors.CustomDateEditor;
 9 import org.springframework.stereotype.Controller;
10 import org.springframework.validation.BindingResult;
11 import org.springframework.validation.ObjectError;
12 import org.springframework.web.bind.WebDataBinder;
13 import org.springframework.web.bind.annotation.InitBinder;
14 import org.springframework.web.bind.annotation.PostMapping;
15 import org.springframework.web.bind.annotation.ResponseBody;
16 
17 import com.demo.po.UserInfo;
18 
19 @Controller
20 public class ValidationController {
21 
22     /**
23      * 
24      * 
25      * @param userInfo
26      * @param result
27      * @return
28      */
29     @PostMapping(value = "member_add")
30     @ResponseBody
31     public Object add(@Valid UserInfo userInfo, BindingResult result) {
32         // 执行的验证出现错误
33         if (result.hasErrors()) {
34             Iterator<ObjectError> iterator = result.getAllErrors().iterator();
35             // 获取全部的错误
36             while (iterator.hasNext()) {
37                 // 取出每一个错误
38                 ObjectError error = iterator.next();
39                 System.out.println("【错误信息】 code = " + error.getCode() + ", message = " + error.getDefaultMessage());
40             }
41             return result.getAllErrors();
42         } else {
43             return userInfo;
44         }
45     }
46 
47     /**
48      * 本程序需要对日期格式进行处理
49      * 
50      * @param binder
51      */
52     @InitBinder
53     public void initBinder(WebDataBinder binder) {
54         // 建立一个可以将字符串转换为日期的程序类
55         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
56         // 明确的描述此时需要注册一个日期格式的转换处理程序
57         binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(sdf, true));
58     }
59 
60 }

然后搞个postman测试一下自己的校验接口是否正常,如下所示:

原文地址:https://www.cnblogs.com/biehongli/p/13955928.html