一、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
二、注解说明
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a317ebdfceb6581ed4d24365a1c182ce.png#pic_center)
三、对实体类进行校验
1、do
@Data
public class User {
@NotNull(message = "用户账号不能为空")
@Size(min = 6, max = 11, message = "账号长度必须是6-11个字符")
private String account;
@NotNull(message = "用户密码不能为空")
@Size(min = 6, max = 11, message = "密码长度必须是6-16个字符")
private String password;
}
2、controller
@RestController
public class UserController {
@PostMapping("/CreateUser")
public void CreateUser(@RequestBody @Validated User user) {
System.out.println("hello");
}
}
3、编写全局统一异常处理
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;
@RestControllerAdvice
public class ExceptionConfig {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Object handleValidException(MethodArgumentNotValidException e) {
JSONObject json = new JSONObject();
json.put("path", req.getRequestURI());
String defaultMessage = exception.getBindingResult().getFieldError().getDefaultMessage();
json.put("code",400);
json.put("success", false);
json.put("msg",defaultMessage);
json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
return json;
}
@ExceptionHandler(value = ConstraintViolationException.class)
public String handleConstraintViolationException(ConstraintViolationException e) {
String message = exception.getLocalizedMessage().split(": ")[1];
JSONObject json = new JSONObject();
json.put("path", req.getRequestURI());
json.put("code",400);
json.put("success", false);
json.put("msg",message);
return json;
}
@ExceptionHandler(value = BindException.class)
public Object validatedGetException(HttpServletRequest req, BindException exception){
JSONObject json = new JSONObject();
json.put("path", req.getRequestURI());
String defaultMessage = exception.getBindingResult().getFieldError().getDefaultMessage();
json.put("code",400);
json.put("success", false);
json.put("msg",defaultMessage);
json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
return json;
}
}
四、针对单个参数进行校验
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotNull;
@RestController
@Validated
public class UserController {
@PostMapping("/query")
public void query(@NotNull(message = "id不能为空") Integer id) {
}
}
五、配置Springboot校验模式
package com.zkzx.layer.config;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
@Configuration
public class ValidatorConfig {
@Bean
public Validator validator() {
ValidatorFactory validatorFactory = Validation
.byProvider(HibernateValidator.class)
.configure()
.failFast(true)
.buildValidatorFactory();
Validator validator = validatorFactory.getValidator();
return validator;
}
}