2个版本(注解和接口),另外加一个自定义注解
一.注解版
1.引入pom
<!--校验-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
2.实体类
import javax.validation.constraints.Max;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
public class User {
@NotBlank(message="名字不能为空")
@Size(min=1, max=4)
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@NotBlank(message="邮箱不能为空")
@Email(message="邮箱格式错误")
private String email;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
3.测试
@RequestMapping("/login")
@ResponseBody
@RequestInfo(description = "cache-page-测试1")
public String testValid(@Valid User user, BindingResult result) {
if (result.hasErrors()) {
List<ObjectError> errorList = result.getAllErrors();
for (ObjectError error : errorList) {
System.out.println(error.getDefaultMessage());
}
}
return "register";
}
二.注解版
1.引入pom
<!--校验-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
2.实体类
public class User {
private String userName;
private int age;
private String email;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
3.校验类
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.oppo.paas.pcache.service.annotation.User;
/**
* 校验接口版(需要对应@Validated)
* 可以自定义校验规则
* @author 80218857
*
*/
public class UserValidator implements Validator {
@Override
public boolean supports(Class<?> arg0) {
return arg0.equals(User.class);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "userName", "user.userName.required", "用户名不能为空");
ValidationUtils.rejectIfEmpty(errors, "email", "user.email.required", "邮箱不能为空");
User user = (User) target;
int length = user.getUserName().length();
if (length > 4) {
errors.rejectValue("userName", "user.userName.too_long", "用户名不能超过{4}个字符");
}
int index = user.getEmail().indexOf("@");
if (index == -1) {
errors.rejectValue("email", "user.email.invalid_email", "邮箱格式错误");
}
}
}
4.测试
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new UserValidator());
}
@RequestMapping("/login2")
@ResponseBody
@RequestInfo(description = "cache-page-测试1")
public String testValid(@Validated User user, BindingResult result) {
if (result.hasErrors()) {
List<ObjectError> errorList = result.getAllErrors();
for (ObjectError error : errorList) {
System.out.println(error.getDefaultMessage());
}
}
return "register";
}
参考:https://blog.csdn.net/u012706811/article/details/51079740
三.自定义注解
1.自定义@Ip
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import com.oppo.paas.pcache.web.validator.IpValidator;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* IP验证
*
* @author Hero
*/
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = IpValidator.class )
public @interface Ip {
String message() default "IP格式不正确";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
校验类
import java.util.regex.Pattern;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import com.example.demo.validator.annotation.Ip;
public class IpValidator implements ConstraintValidator<Ip, String> {
private String ipReg = "^(([1-9]|([1-9]\\d)|(1\\d\\d)|(2([0-4]\\d|5[0-5])))\\.)(([1-9]|([1-9]\\d)|(1\\d\\d)|(2([0-4]\\d|5[0-5])))\\.){2}([1-9]|([1-9]\\d)|(1\\d\\d)|(2([0-4]\\d|5[0-5])))$";// ip的正则表达式
private Pattern ipPattern = Pattern.compile(ipReg);
@Override
public void initialize(Ip constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null)
return true;
return ipPattern.matcher(value).matches();
}
}
2.使用@Ip
同一
例:
@Ip(message = "IP格式错误")
private String ip;