springboot整合jsr303校验规则
作者:互联网
1.pom引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.实体类定义校验规则
public class User {
@NotEmpty(message = "不能为空")
private String name;
@Pattern(regexp = "[0-9]*[a-z]*[0-9]*",message = "格式错误")
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
3.控制类入参加上注解
@RestController
public class TestController {
@RequestMapping("/valid")
public String valid(@Validated User user) throws Exception {
return "";
}
}
4.定义全局异常处理类
@RestControllerAdvice
public class GlobalExceptionHandle {
/**
* 处理全局异常
*
* @param e 异常信息
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result customHandler(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
for (FieldError fieldError : bindingResult.getFieldErrors()) {
return Result.ofFail(-1, fieldError.getDefaultMessage());
}
return Result.ofSuccessMsg("");
}
}
不定义全局异常处理 进行校验的方式
在方法入参最后加上 BindingResult bindingResult ,然后从bindingResult中获取异常,并进行处理
@RequestMapping("/valid")
public String valid(@Validated User user, BindingResult bindingResult) throws Exception {
if (bindingResult.hasErrors()) {
for (FieldError fieldError : bindingResult.getFieldErrors()) {
throw new EarthquakeException(-1, fieldError.getDefaultMessage());
}
}
return "";
}
标签:return,String,name,jsr303,校验,public,pwd,bindingResult,springboot 来源: https://blog.csdn.net/weixin_46176823/article/details/120270469