方法一:使用hibernate-validate框架,使用起来较为麻烦(SpringMVC官方推荐);
方法二:使用aop面向切面和自定义注解;
拦截器与aop:
aop可以取得被代理方法的对象和参数,而拦截器需要从请求中取值在校验,且校验规则也不好取得。
步骤:
1、定义注解
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ValidateParam {
Validatefiled[] fileds();
}
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Validatefiled {
boolean notNull() default false;
int maxLength() default -1;
int minLength() default -1;
String regex() default "";