1.导入所需要的启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.在controller层接口方法上加注解@Valid
@GetMapping("/text1")
public String text4(@Valid User user){
return "read Ok";
}
3.在实现类上增加注解,并设置message的值
public class User {
@NotNull(message = "用户名不能为空") //不能是空
private int id;
private String name;
@ApiModelProperty(name = "sex", value = "用户性别")
private String sex;
@NotNull(message = "邮箱不能为空")
@Email(message = "邮箱格式不正确")
private String email;
}
4.全局异常的捕捉,因为这个异常是BindException,所以需要用BindException
在跟包下新建expception层
// 全部参数一起校验捕获异常,并打印
@ExceptionHandler(BindException.class)
public String handlerDataBindException(Exception e){
BindException be=(BindException) e;
return be.getBindingResult().getFieldError().getDefaultMessage();
}