spring自定义校验注解

自定义校验注解

  1. 引入validation模块

		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-validationartifactId>
		dependency>
  1. 新建注解
@Target({ ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {UserNameValidator.class  })
public @interface UserNameValidate {
	// return message
	String message();
	// TODO: must add groups and payload method
	// or system will throw error 'not contain a groups/payload parameter.'
	Class<?>[] groups() default {};
	Class<? extends Payload>[] payload() default {};

}
  1. 新建validator
public class UserNameValidator implements ConstraintValidator<UserNameValidate, String> {
	public boolean isValid(String userName, ConstraintValidatorContext context) {
		if(userName == null) {
			return false;
		}
		return true;
	}
}
  1. 新建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;
		}
	}
}
  1. 打开浏览器输入url: http://localhost:8080/register/user,输出结果:user name is not valid
  2. 分组校验
  3. 顺序校验

你可能感兴趣的:(Spring,Boot,springboot)