1、定义错误信息

在resources/下创建名称为ValidationMessages.properties (.ymal 、 .yml)

member.mid.notnull.error=用户名不允许为空
member.mid.email.error=用户名的注册必须输入正确的邮箱
member.mid.length.error=用户名的格式错误

2、给Vo类添加注解

package com.zemel.micorboot.vo;
 
import java.io.Serializable;
import java.util.Date;
 
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
 
import org.hibernate.validator.constraints.Length;
 
public class Member implements Serializable{
 
	/** * */
	private static final long serialVersionUID = 1L;
 
	@NotNull(message="{member.mid.notnull.error}")
	@Email(message="{member.mid.email.error}")
	@Length(min=6,message="{member.mid.length.error}")
	private String mid;
	
	private Integer age;
	private Double salary;
	private Date birthday;
	public String getMid() {
		return mid;
	}
	public void setMid(String mid) {
		this.mid = mid;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	
}

3、控制添加验证

@Valid Member vo, BindingResult result


package com.zemel.micorboot.controller;
 
import java.util.List;
 
import javax.validation.Valid;
 
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.zemel.micorboot.base.AbstractBaseController;
import com.zemel.micorboot.vo.Member;
 
@Controller
public class MemberController extends AbstractBaseController {
	
	@GetMapping("/addPre")
	public String addPre(){
		return "message/member_add";
	}
 
	@GetMapping("/add")
	@ResponseBody
	public Object add(@Valid Member vo, BindingResult result){
		System.out.println("【ADD方法】"+result.hasErrors());
		
		if(result.hasErrors()){
			List<ObjectError> list = result.getAllErrors();
			list.forEach(oe -> {
				
			});
			return result.getAllErrors();
		}
		return vo; 
	}
}

4、访问结果

[{
    "codes": [
        "Email.member.mid",
        "Email.mid",
        "Email.java.lang.String",
        "Email"
    ],
    "arguments": [{
            "codes": [
                "member.mid",
                "mid"
            ],
            "arguments": null,
            "defaultMessage": "mid",
            "code": "mid"
        },
        [],
        {
            "defaultMessage": ".*",
            "arguments": null,
            "codes": [".*"]
        }
    ],
    "defaultMessage": "ç¨æ·åç注åå¿é¡»è¾å¥æ­£ç¡®çé®ç®±",
    "objectName": "member",
    "field": "mid",
    "rejectedValue": "xx",
    "bindingFailure": false,
    "code": "Email"
}]


原理上和 Hibernate Validator 相关