一、添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
二、实体类中添加校验规则注解
package cn.bounter.validation.entity; import lombok.Data; import lombok.experimental.Accessors; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; @Data @Accessors(chain = true) public class Bounter { @NotBlank private String name; @Min(18) private Integer age; }
JSR-303常用注解如下:
//空检查
@NotNull 对象不为null
@NotBlank 字符串不为null且不是”“
@NotEmpty 集合不为null且不为空
//长度检查
@Size(min = 1, max = 10) 字符串长度或集合大小
@Length 字符串长度
//数值检查
@Min(1)
@Max(10)
@Range(min = 1, max = 10)
@Range(min = 1, max = 10)
//其他
@Email
@AssertTrue
@AssertFalse
三、开启校验(开启后请求时会自动触发校验,校验失败抛出异常)
package cn.bounter.validation.controller; import cn.bounter.validation.common.ResponseData; import cn.bounter.validation.entity.Bounter; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/bounter") public class BounterController { @PostMapping public ResponseData<?> post(@Validated Bounter bounter) { return ResponseData.ok(bounter); } @PostMapping("/json") public ResponseData<?> postJson(@Validated @RequestBody Bounter bounter) { return ResponseData.ok(bounter); } @GetMapping public ResponseData<?> get(@Validated Bounter bounter) { return ResponseData.ok(bounter); } }
四、统一处理校验异常,并返回错误提示
package cn.bounter.validation.common; import org.springframework.validation.BindException; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.stream.Collectors; @RestControllerAdvice public class AppExceptionHandler { /** * 处理不带任何注解的参数绑定校验异常 * @param e * @return */ @ExceptionHandler(BindException.class) public ResponseData<?> handleBingException(BindException e) { String errorMsg = e.getBindingResult().getAllErrors() .stream() .map(objectError -> ((FieldError)objectError).getField() + ((FieldError)objectError).getDefaultMessage()) .collect(Collectors.joining(",")); //"errorMsg": "name不能为空,age最小不能小于18" return new ResponseData<>().fail(errorMsg); } /** * 处理 @RequestBody参数校验异常 * @param e * @return */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseData<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { String errorMsg = e.getBindingResult().getAllErrors() .stream() .map(objectError -> ((FieldError)objectError).getField() + ((FieldError)objectError).getDefaultMessage()) .collect(Collectors.joining(",")); //"errorMsg": "name不能为空,age最小不能小于18" return new ResponseData<>().fail(errorMsg); } }
五、如需要手动触发校验,则可使用下面的方式
package cn.bounter.validation; import cn.bounter.validation.entity.Bounter; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.validation.ConstraintViolation; import javax.validation.Validator; import java.util.Set; @RunWith(SpringRunner.class) @SpringBootTest public class BounterValidationApplicationTests { //参数校验器 @Autowired private Validator validator; /** * 测试手动触发校验 */ @Test public void testValidation() { Bounter bounter = new Bounter().setName("").setAge(17); Set<ConstraintViolation<Bounter>> violationSet = validator.validate(bounter); violationSet.forEach(violation -> { //name不能为空 //age最小不能小于18 System.out.println(violation.getPropertyPath() + violation.getMessage()); }); } }
这就是全部的步骤了,是不是觉得的挺简单的哉!那就赶快自己动手试试吧!