1.引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> <version>3.1.2</version> </dependency>
2:实体类
实体类属性加上@NotNull注解 例:@NotNull(message = "id不能为空")
public class People {
private Integer bizCode;
@NotNull(message = "id不能为空")
private Long id;
private String name;
private Integer age;
private String address;
private String userName;
private String pwd;
private String email;
private String phonenumber;
private String sex;
public Long getId() {
return id;
}
public Integer getBizCode() {
return bizCode;
}
public void setBizCode(Integer bizCode) {
this.bizCode = bizCode;
}
public void setId(Long 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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
@JsonIgnore
@JsonProperty
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
3:controller 加上@Valid 注解
@RestController
public class PeopleController {
@PostMapping("save")
public AjaxResult save( @RequestBody @Valid People people) {
System.out.println(people);
return AjaxResult.success( people );
}
}
4:创建全局异常类,捕获异常
/**
* 全局异常处理器
*/
@RestControllerAdvice
public class GlobalExceptionHandler
{
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 自定义验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
{
log.error(e.getMessage(), e);
String message = e.getBindingResult().getFieldError().getDefaultMessage();
return AjaxResult.error(message);
}
}
5:postman测试
不传id测试
传入id测试