先定义两个注解类ValidateGroup 和 ValidateFiled
ValidateGroup .java
- package com.zf.ann;
-
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.METHOD)
- public @interface ValidateGroup {
- public ValidateFiled[] fileds() ;
- }
ValidateFiled.java
- package com.zf.ann;
-
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.METHOD)
- public @interface ValidateFiled {
-
-
- public int index() default -1 ;
-
-
- public String filedName() default "" ;
-
-
- public String regStr() default "";
-
-
- public boolean notNull() default false;
-
-
- public int maxLen() default -1 ;
-
-
- public int minLen() default -1 ;
-
-
- public int maxVal() default -1 ;
-
-
- public int minVal() default -1 ;
-
- }
注解处理类
ValidateAspectHandel.java
- package com.zf.aspet;
- import java.lang.annotation.Annotation;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
-
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.Around;
- import org.aspectj.lang.annotation.Aspect;
- import org.springframework.stereotype.Component;
- import org.springframework.web.servlet.ModelAndView;
-
- import com.zf.ann.ValidateFiled;
- import com.zf.ann.ValidateGroup;
- @Component
- @Aspect
- public class ValidateAspectHandel {
-
-
- @SuppressWarnings({ "finally", "rawtypes" })
- @Around("@annotation(com.zf.ann.ValidateGroup)")
- public Object validateAround(ProceedingJoinPoint joinPoint) throws Throwable {
- boolean flag = false ;
- ValidateGroup an = null;
- Object[] args = null ;
- Method method = null;
- Object target = null ;
- String methodName = null;
- try{
- methodName = joinPoint.getSignature().getName();
- target = joinPoint.getTarget();
- method = getMethodByClassAndName(target.getClass(), methodName);
- args = joinPoint.getArgs();
- an = (ValidateGroup)getAnnotationByMethod(method ,ValidateGroup.class );
- flag = validateFiled(an.fileds() , args);
- }catch(Exception e){
- flag = false;
- }finally{
- if(flag){
- System.out.println("验证通过");
- return joinPoint.proceed();
- }else{
- System.out.println("验证未通过");
- Class returnType = method.getReturnType();
- if(returnType == String.class){
- return "/error.jsp";
- }else if(returnType == ModelAndView.class){
- return new ModelAndView("/error.jsp");
- }else{
- return null ;
- }
- }
- }
- }
-
-
- public boolean validateFiled( ValidateFiled[] valiedatefiles , Object[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException{
- for (ValidateFiled validateFiled : valiedatefiles) {
- Object arg = null;
- if("".equals(validateFiled.filedName()) ){
- arg = args[validateFiled.index()];
- }else{
- arg = getFieldByObjectAndFileName(args[validateFiled.index()] ,
- validateFiled.filedName() );
- }
-
- if(validateFiled.notNull()){
- if(arg == null )
- return false;
- }else{
- if(arg == null )
- return true;
- }
-
- if(validateFiled.maxLen() > 0){
- if(((String)arg).length() > validateFiled.maxLen())
- return false;
- }
-
- if(validateFiled.minLen() > 0){
- if(((String)arg).length() < validateFiled.minLen())
- return false;
- }
-
- if(validateFiled.maxVal() != -1){
- if( (Integer)arg > validateFiled.maxVal())
- return false;
- }
-
- if(validateFiled.minVal() != -1){
- if((Integer)arg < validateFiled.minVal())
- return false;
- }
-
- if(!"".equals(validateFiled.regStr())){
- if(arg instanceof String){
- if(!((String)arg).matches(validateFiled.regStr()))
- return false;
- }else{
- return false;
- }
- }
- }
- return true;
- }
-
-
- public Object getFieldByObjectAndFileName(Object targetObj , String fileName) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
- String tmp[] = fileName.split("\\.");
- Object arg = targetObj ;
- for (int i = 0; i < tmp.length; i++) {
- Method methdo = arg.getClass().
- getMethod(getGetterNameByFiledName(tmp[i]));
- arg = methdo.invoke(arg);
- }
- return arg ;
- }
-
-
- public String getGetterNameByFiledName(String fieldName){
- return "get" + fieldName.substring(0 ,1).toUpperCase() + fieldName.substring(1) ;
- }
-
-
- public Annotation getAnnotationByMethod(Method method , Class annoClass){
- Annotation all[] = method.getAnnotations();
- for (Annotation annotation : all) {
- if (annotation.annotationType() == annoClass) {
- return annotation;
- }
- }
- return null;
- }
-
-
- public Method getMethodByClassAndName(Class c , String methodName){
- Method[] methods = c.getDeclaredMethods();
- for (Method method : methods) {
- if(method.getName().equals(methodName)){
- return method ;
- }
- }
- return null;
- }
-
- }
需要验证参数的Control方法
- package com.zf.service;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.servlet.ModelAndView;
- import com.zf.ann.ValidateFiled;
- import com.zf.ann.ValidateGroup;
- import com.zf.vo.Person;
-
- @Controller("PersonControl")
- public class PersonControl {
-
-
- @ValidateGroup(fileds = {
-
- @ValidateFiled(index=0 , notNull=true ) ,
-
- @ValidateFiled(index=0 , notNull=true , filedName="id" , minVal = 3) ,
-
- @ValidateFiled(index=0 , notNull=true , filedName="name" , maxLen = 10 , minLen = 3 ) ,
-
- @ValidateFiled(index=1 , notNull=true , maxLen = 5 , minLen = 2 ) ,
- @ValidateFiled(index=2 , notNull=true , maxVal = 100 , minVal = 18),
- @ValidateFiled(index=3 , notNull=false , regStr= "^\\w+@\\w+\\.com$" )
- })
- @RequestMapping("savePerson")
- public ModelAndView savePerson(Person person , String name , int age , String email){
- ModelAndView mav = new ModelAndView("/index.jsp");
- System.out.println("addPerson()方法调用成功!");
- return mav ;
- }
-
- }
application.xml配置
测试
- package com.zf.test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.zf.service.PersonControl;
- import com.zf.vo.Person;
- public class PersonTest {
- public static void main(String[] args) {
- ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
- PersonControl ps = (PersonControl) ac.getBean("PersonControl"); //测试
- ps.savePerson(new Person(3, "qqq") , "sss" , 100 , "243970446@qq.com");
- }
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <context:component-scan base-package="com.*"></context:component-scan>
- <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
- </beans>
Spring AOP实现 Bean字段合法性校验
原文:http://www.cnblogs.com/barrywxx/p/6964257.html