自定义校验注解
- 引入validation模块
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
- 新建注解
@Target({ ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {UserNameValidator.class })
public @interface UserNameValidate {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
- 新建validator
public class UserNameValidator implements ConstraintValidator<UserNameValidate, String> {
public boolean isValid(String userName, ConstraintValidatorContext context) {
if(userName == null) {
return false;
}
return true;
}
}
- 新建controller
@RestController
@RequestMapping("/register")
public class RegisterController {
@RequestMapping("/user")
public String register(@Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return bindingResult.getFieldError().getDefaultMessage();
}
return "register success";
}
class User {
public User() {
}
@UserNameValidate(message = "user name is not valid")
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
}
- 打开浏览器输入url: http://localhost:8080/register/user,输出结果:user name is not valid
- 分组校验
- 顺序校验
|