一、Validator注解校验数据
目的是校验传入的参数是否符合要求
- 在pom.xml中加入hibernate-validator依赖
<!--hibernate注解-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.4.Final</version>
</dependency>
- 在Dto或request中定义一个对象类UserRequest
@Data
@ToString
public class UserRequest implements Serializable {
@NotBlank
private String name;
@NotBlank
private String sex;
@NotNull
@Min(18)
private Integer age;
}
其中的@NotBlank,@NotNull,@Min(18)都是注解校验,不为空,最小18。
- Controller中新建一个ValidateController,调用对象UserRequest,并且在前面加@Validated。
@RestController
public class ValidateController {
private static final Logger log = (Logger) LoggerFactory.getLogger(ValidateController.class);
private static final String prefix = "/validate";
@RequestMapping(value = prefix+"/insert",method = RequestMethod.POST)
//调用对象,并有修饰@Validated
public BaseResponse insert(@RequestBody @Validated UserRequest userRequest, BindingResult result){
BaseResponse baseResponse = new BaseResponse(StatusCode.Success);
try {
if(result.hasErrors()){
baseResponse = new BaseResponse(StatusCode.Invalid_Params);
}
log.info("前端接收到的数据是:{}",userRequest);
}catch (Exception e){
baseResponse = new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
e.printStackTrace();
}
return baseResponse;
}
}
二、自定义注解
1.新建文件夹annotation
在里面新建一个接口
@Documented
@Constraint(validatedBy = SexValidation.class)
@Target({ElementType.FIELD,ElementType.ANNOTATION_TYPE,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface SexAnnotation {
String message() default "性别校验取值为:1=男,2=女";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
2.新建文件夹validate
在里面新建一个类
public class SexValidation implements ConstraintValidator<SexAnnotation,Integer> {
Set<Integer> sexArr;
@Override
public void initialize(SexAnnotation constraintAnnotation) {
sexArr = new HashSet<Integer>();
sexArr.add(1);
sexArr.add(2);
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
if(sexArr.contains(value)){
return true;
}else{
return false;
}
}
}
3.使用时,在用户对象UserRequest的sex属性前使用SexAnnotation
@SexAnnotation
private Integer sex;
题外
CRUD:create,retrieve,update,delete,用于描述软件系统中database或持久层的基本操作