第17篇:参数校验
校验方式
-
业务层使用代码校验,如
public List<Student> getStudents(Student stu) { // 姓名、性别(0或1表示)、年龄、专业、手机号、邮箱 if (Objects.nonNull(stu)) { .. } if (StringUtils.isBlank(stu.name)) { .. } if (stu.sex < 0 || stu.sex > 1) { .. } if (stu.age < 6 || stu.age > 60 ) { .. } if (!StringUtils.equals(stu.subject, "英语")) { // 只支持英语专业的stu info查询 } // 正则表达式验证手机号:\d{11} // 正则表达式验证邮箱:'[a-zA-Z0-9_-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+' if () }
-
JSR-303
注解类型 包括及说明 空检查 @Null @NotNull
@NotBlack @NotEmptyBoolean检查 @AssertTrue
@AssertFalse长度检查 @Size
@Length日期检查 @Past
@Future
@Pattern数值检查 @Min @Max
@DecimalMin @DecimalMax
@Digits
@Range正则检查 @CreditCardNumber
@Email
@ScriptAssert
@URL递归校验 @Valid 1. 注解作用在Java Bean或REST接口参数 (过度处理:BindingResult) 2. 全局异常处理器
demo
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.使用
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
@Length(min = 4, max = 6)
private String id;
@NotBlank
private String name;
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate birth;
@JsonIgnore
private String desc;
}
3.控制器REST接口:@Valid
@PostMapping("/")
public Person get(@RequestBody @Valid Person person) {
Person per = personInMemory.get(person.getId());
return per == null ? new Person() : per;
}
输出
通过id过滤,其他字段填充用(要求:id长度[4,6],name非空白)
成功请求
POST localhost:8080/person/
{
"id": "1111",
"name": "c",
"birth": "2020-10-13"
}
错误请求:id长度不对
POST localhost:8080/person/
{
"id": "1",
"name": "c",
"birth": "2020-10-13"
}
日志:codes [person.id,id]; arguments []; default message [id],6,4]; default message [长度需要在4和6之间]] ]
处理@Valid异常:MethodArgumentNotValidException
添加全局异常处理器
@ControllerAdvice
public class ExcepHandler {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResponseEntity<Object> validFailure(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
}
}
此处请求id长度不符合时,会使用这个异常处理器进行处理返回,返回结果如下:状态码400
{
"id": "长度需要在4和6之间"
}
非controller接口验证,例如Service
1.service添加类注解:@Validated
2.方法使用@Valid
3.全局异常处理器
参考
https://www.cnblogs.com/huaweiyun/p/13673568.html
https://juejin.im/post/6844903991621451789#heading-5