(原文地址:http://blog.csdn.net/is_zhoufeng/article/details/7683194

1、依赖包

   aspectjweaver.jar

其中Maven的配置

可以参考   利用Spring AOP自定义注解解决日志和签名校验 http://www.cnblogs.com/shipengzhi/articles/2716004.html

2、验证相关类

   共三个类,分别是

   ValidateGroup.java | ValidateFiled.java | ValidateAspectHandel.java

先定义两个注解类ValidateGroup 和 ValidateFiled

ValidateGroup .java

  1. package com.zf.ann;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. @Retention(RetentionPolicy.RUNTIME)
  7. @Target(ElementType.METHOD)
  8. public @interface ValidateGroup {
  9. public ValidateFiled[] fileds() ;
  10. }

ValidateFiled.java

  1. package com.zf.ann;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. @Retention(RetentionPolicy.RUNTIME)
  7. @Target(ElementType.METHOD)
  8. public @interface ValidateFiled {
  9. /**
  10. * 参数索引位置
  11. */
  12. public int index() default -1 ;
  13. /**
  14. * 如果参数是基本数据类型或String ,就不用指定该参数,如果参数是对象,要验证对象里面某个属性,就用该参数指定属性名
  15. */
  16. public String filedName() default "" ;
  17. /**
  18. * 正则验证
  19. */
  20. public String regStr() default "";
  21. /**
  22. * 是否能为空  , 为true表示不能为空 , false表示能够为空
  23. */
  24. public boolean notNull() default false;
  25. /**
  26. * 最大长度  , 用于验证字符串
  27. */
  28. public int maxLen() default -1 ;
  29. /**
  30. * 最小长度 , 用于验证字符串
  31. */
  32. public int minLen() default -1 ;
  33. /**
  34. *最大值 ,用于验证数字类型数据
  35. */
  36. public int maxVal() default -1 ;
  37. /**
  38. *最小值 ,用于验证数值类型数据
  39. */
  40. public int minVal() default -1 ;
  41. }

注解处理类

ValidateAspectHandel.java

  1. package com.zf.aspet;
  2. import java.lang.annotation.Annotation;
  3. import java.lang.reflect.InvocationTargetException;
  4. import java.lang.reflect.Method;
  5. import org.aspectj.lang.ProceedingJoinPoint;
  6. import org.aspectj.lang.annotation.Around;
  7. import org.aspectj.lang.annotation.Aspect;
  8. import org.springframework.stereotype.Component;
  9. import org.springframework.web.servlet.ModelAndView;
  10. import com.zf.ann.ValidateFiled;
  11. import com.zf.ann.ValidateGroup;
  12. /**
  13. * 验证注解处理类
  14. * @author zhoufeng
  15. */
  16. @Component
  17. @Aspect
  18. public class ValidateAspectHandel {
  19. /**
  20. * 使用AOP对使用了ValidateGroup的方法进行代理校验
  21. * @throws Throwable
  22. */
  23. @SuppressWarnings({ "finally", "rawtypes" })
  24. @Around("@annotation(com.zf.ann.ValidateGroup)")
  25. public Object validateAround(ProceedingJoinPoint joinPoint) throws Throwable  {
  26. boolean flag = false ;
  27. ValidateGroup an = null;
  28. Object[] args =  null ;
  29. Method method = null;
  30. Object target = null ;
  31. String methodName = null;
  32. try{
  33. methodName = joinPoint.getSignature().getName();
  34. target = joinPoint.getTarget();
  35. method = getMethodByClassAndName(target.getClass(), methodName);    //得到拦截的方法
  36. args = joinPoint.getArgs();     //方法的参数
  37. an = (ValidateGroup)getAnnotationByMethod(method ,ValidateGroup.class );
  38. flag = validateFiled(an.fileds() , args);
  39. }catch(Exception e){
  40. flag = false;
  41. }finally{
  42. if(flag){
  43. System.out.println("验证通过");
  44. return joinPoint.proceed();
  45. }else{  //这里使用了Spring MVC ,所有返回值应该为Strng或ModelAndView ,如果是用Struts2,直接返回一个String的resutl就行了
  46. System.out.println("验证未通过");
  47. Class returnType = method.getReturnType();  //得到方法返回值类型
  48. if(returnType == String.class){ //如果返回值为Stirng
  49. return "/error.jsp";        //返回错误页面
  50. }else if(returnType == ModelAndView.class){
  51. return new ModelAndView("/error.jsp");//返回错误页面
  52. }else{  //当使用Ajax的时候 可能会出现这种情况
  53. return null ;
  54. }
  55. }
  56. }
  57. }
  58. /**
  59. * 验证参数是否合法
  60. */
  61. public boolean validateFiled( ValidateFiled[] valiedatefiles , Object[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException{
  62. for (ValidateFiled validateFiled : valiedatefiles) {
  63. Object arg = null;
  64. if("".equals(validateFiled.filedName()) ){
  65. arg = args[validateFiled.index()];
  66. }else{
  67. arg = getFieldByObjectAndFileName(args[validateFiled.index()] ,
  68. validateFiled.filedName() );
  69. }
  70. if(validateFiled.notNull()){        //判断参数是否为空
  71. if(arg == null )
  72. return false;
  73. }else{      //如果该参数能够为空,并且当参数为空时,就不用判断后面的了 ,直接返回true
  74. if(arg == null )
  75. return true;
  76. }
  77. if(validateFiled.maxLen() > 0){      //判断字符串最大长度
  78. if(((String)arg).length() > validateFiled.maxLen())
  79. return false;
  80. }
  81. if(validateFiled.minLen() > 0){      //判断字符串最小长度
  82. if(((String)arg).length() < validateFiled.minLen())
  83. return false;
  84. }
  85. if(validateFiled.maxVal() != -1){   //判断数值最大值
  86. if( (Integer)arg > validateFiled.maxVal())
  87. return false;
  88. }
  89. if(validateFiled.minVal() != -1){   //判断数值最小值
  90. if((Integer)arg < validateFiled.minVal())
  91. return false;
  92. }
  93. if(!"".equals(validateFiled.regStr())){ //判断正则
  94. if(arg instanceof String){
  95. if(!((String)arg).matches(validateFiled.regStr()))
  96. return false;
  97. }else{
  98. return false;
  99. }
  100. }
  101. }
  102. return true;
  103. }
  104. /**
  105. * 根据对象和属性名得到 属性
  106. */
  107. public Object getFieldByObjectAndFileName(Object targetObj , String fileName) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
  108. String tmp[] = fileName.split("\\.");
  109. Object arg = targetObj ;
  110. for (int i = 0; i < tmp.length; i++) {
  111. Method methdo = arg.getClass().
  112. getMethod(getGetterNameByFiledName(tmp[i]));
  113. arg = methdo.invoke(arg);
  114. }
  115. return arg ;
  116. }
  117. /**
  118. * 根据属性名 得到该属性的getter方法名
  119. */
  120. public String getGetterNameByFiledName(String fieldName){
  121. return "get" + fieldName.substring(0 ,1).toUpperCase() + fieldName.substring(1) ;
  122. }
  123. /**
  124. * 根据目标方法和注解类型  得到该目标方法的指定注解
  125. */
  126. public Annotation getAnnotationByMethod(Method method , Class annoClass){
  127. Annotation all[] = method.getAnnotations();
  128. for (Annotation annotation : all) {
  129. if (annotation.annotationType() == annoClass) {
  130. return annotation;
  131. }
  132. }
  133. return null;
  134. }
  135. /**
  136. * 根据类和方法名得到方法
  137. */
  138. public Method getMethodByClassAndName(Class c , String methodName){
  139. Method[] methods = c.getDeclaredMethods();
  140. for (Method method : methods) {
  141. if(method.getName().equals(methodName)){
  142. return method ;
  143. }
  144. }
  145. return null;
  146. }
  147. }

需要验证参数的Control方法

  1. package com.zf.service;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.servlet.ModelAndView;
  5. import com.zf.ann.ValidateFiled;
  6. import com.zf.ann.ValidateGroup;
  7. import com.zf.vo.Person;
  8. @Controller("PersonControl")
  9. public class PersonControl {
  10. //下面方法 ,是需要验证参数的方法
  11. @ValidateGroup(fileds = {
  12. //index=0 表示下面方法的第一个参数,也就是person  nutNull=true 表示不能为空
  13. @ValidateFiled(index=0 , notNull=true ) ,
  14. //index=0 表示第一个参数  filedName表示该参数的一个属性 ,也就是person.id 最小值为3 也就是 person.id 最小值为3
  15. @ValidateFiled(index=0 , notNull=true , filedName="id" , minVal = 3) ,
  16. //表示第一个参数的name 也就是person.name属性最大长度为10,最小长度为3
  17. @ValidateFiled(index=0 , notNull=true , filedName="name" , maxLen = 10 , minLen = 3 ) ,
  18. //index=1 表示第二个参数最大长度为5,最小长度为2
  19. @ValidateFiled(index=1 , notNull=true , maxLen = 5 , minLen = 2 ) ,
  20. @ValidateFiled(index=2 , notNull=true , maxVal = 100 , minVal = 18),
  21. @ValidateFiled(index=3 , notNull=false , regStr= "^\\w+@\\w+\\.com$" )
  22. })
  23. @RequestMapping("savePerson")
  24. public ModelAndView savePerson(Person person , String name , int age , String email){
  25. ModelAndView mav = new ModelAndView("/index.jsp");
  26. System.out.println("addPerson()方法调用成功!");
  27. return mav ;        //返回index.jsp视图
  28. }
  29. }

application.xml配置

测试

  1. package com.zf.test;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. import com.zf.service.PersonControl;
  5. import com.zf.vo.Person;
  6. public class PersonTest {
  7. public static void main(String[] args) {
  8. ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
  9. PersonControl ps = (PersonControl) ac.getBean("PersonControl"); //测试
  10. ps.savePerson(new Person(3, "qqq") , "sss" , 100 , "243970446@qq.com");
  11. }
  12. }
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    5. xmlns:context="http://www.springframework.org/schema/context"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    8. http://www.springframework.org/schema/tx
    9. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    10. http://www.springframework.org/schema/aop
    11. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    12. http://www.springframework.org/schema/context
    13. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    14. <context:component-scan base-package="com.*"></context:component-scan>
    15. <!-- 启动对@AspectJ注解的支持 -->
    16. <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
    17. </beans>

springmvc的配置文件中还要加上<aop:aspectj-autoproxy proxy-target-class="true" />:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 通知spring使用cglib而不是jdk的来生成代理方法 AOP可以拦截到Controller,实现参数校验 -->
<aop:aspectj-autoproxy proxy-target-class="true" />

使用SpringAop 验证方法参数是否合法的更多相关文章

  1. 使用Spring Aop验证方法参数是否合法

    先定义两个注解类ValidateGroup 和 ValidateFiled ValidateGroup .java package com.zf.ann; import java.lang.annot ...

  2. 封装jQuery Validate扩展验证方法

    一.封装自定义验证方法-validate-methods.js /***************************************************************** j ...

  3. ASP.NET开发中主要的字符验证方法-JS验证、正则表达式、验证控件、后台验证

    ASP.NET开发中主要的字符验证方法-JS验证.正则表达式.验证控件.后台验证 2012年03月19日 星期一 下午 8:53 在ASP.NET开发中主要的验证方法收藏 <1>使用JS验 ...

  4. JQuery扩展插件Validate—5添加自定义验证方法

    从前面的示例中不难看出validate中自带的验证方法足以满足一般的要求,对于特别的要求可以使用addMethod(name,method,message)添加自定义的验证规则,下面的示例中添加了一个 ...

  5. jQuery Validate自定义各种验证方法(转)

    一.封装自定义验证方法-validate-methods.js /***************************************************************** j ...

  6. jquery validate 自定义验证方法

    query validate有很多验证规则,但是更多的时候,需要根据特定的情况进行自定义验证规则. 这里就来聊一聊jquery validate的自定义验证. jquery validate有一个方法 ...

  7. jqery validate、validate自定义验证方法 + jaery form Demo

    校验规则 required:true  必输字段 remote:"check.php"  使用ajax方法调用check.php验证输入值 email:true  必须输入正确格式 ...

  8. Ubuntu 固态硬盘 4K对齐及启用 Trim,及其验证方法

    因为之前一个移动硬盘因为坏道蔓延导致没办法继续使用,我略冲动地跑去买了一块 120GB 的三星840 固态硬盘回来.为了使用起来更方便,还去弄了个光驱位硬盘托架,把固态硬盘接在了光驱位与原本的笔记本硬 ...

  9. jquery validate 自定义验证方法 日期验证

    jquery validate有很多验证规则,但是更多的时候,需要根据特定的情况进行自定义验证规则. 这里就来聊一聊jquery validate的自定义验证. jquery validate有一个方 ...

随机推荐

  1. Oracle数据类型对应Java类型

    SQL数据类型 JDBC类型代码 标准的Java类型 Oracle扩展的Java类型   1.0标准的JDBC类型:     CHAR java.sql.Types.CHAR java.lang.St ...

  2. 重学C++ (1)

    写在开头的话:这学期没有写太多的代码,终于把中英文两篇论文弄完了,趁着中间的空隙,想想找工作的处境.自己也定了自己的方向.不管学什么语言吧,每个语言都有自己的优势和使用的群体.只要自己是良马,终会有伯 ...

  3. PHP利用微信跳转的Code参数获取用户的openid

    //获取微信登录用户信息function getOpenID($appid,$appsecret,$code){   $url="https://api.weixin.qq.com/sns/ ...

  4. spring-cloud-turbine

    turbine主要用于聚合hystrix的监控数据 依赖pom <dependencyManagement> <dependencies> <dependency> ...

  5. Class<Object>与Class<?>有何区别呢

    1.? 和 Object 差不多,不过还是有差别.在这种情况下: class<? extends SomeClass> , Object就不能用了 Object是一个具体的类名,而?是一个 ...

  6. “Cache-control”常见的取值有private、no-cache、max-age、must-revalidate等

    网页的缓存由HTTP消息头中的"Cache-Control" 来控制的,常见的取值有private.no-cache.max-age.must-revalidate等,默认为pri ...

  7. 在linux下配置Nginx+Java+PHP的环境

    Apache对Java的支持很灵活,它们的结合度也很高,例如Apache+Tomcat和Apache+resin等都可以实现对Java应用 的支持.Apache一般采用一个内置模块来和Java应用服务 ...

  8. ubuntu12.04 server + apache2 + wsgi + django1.6 部署

    最近在学Python和Django,想自己部署一个服务器试试 环境:ubuntu12.04 server | apache2 | django1.6 | python2.7 | mod_wsgi 在网 ...

  9. Linux学习系列之Linux入门(二)Vim学习

    第二篇 Vim学习 主要内容: 基本命令: 插件扩展: 参考资料: vim是一个命令控制的文本编辑器,可以完成几乎我们想要做的所有工作,除了Emacs几乎没有其他的工具能和它匹敌.官方网站是:http ...

  10. TabControl控件

    private void Form1_Load(object sender, EventArgs e) { #region 显示样式 tabControl1.ImageList = imageList ...