先定义两个注解类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. * 是否能为空  , 为true表示不能为空 , false表示能够为空
  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. <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
    16. </beans>

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

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

    (原文地址:http://blog.csdn.net/is_zhoufeng/article/details/7683194) 1.依赖包    aspectjweaver.jar 其中Maven的配 ...

  2. Spring MVC控制器方法参数类型

    HttpServletRequest Spring会自动将 Servlet API 作为参数传过来 HttpServletResponse InputStream 相当于request.getInpu ...

  3. Spring AOP获取方法的参数名称和参数值

    aop配置: <aop:aspectj-autoproxy expose-proxy="true" /> @Before(value = "execution ...

  4. Spring AOP执行方法

      execution(* springinaction.springidol.Instrument.play(..)) * 代表返回为任意类型 springinaction.springidol.I ...

  5. Spring AOP实现 Bean字段合法性校验

    使用SpringAop 验证方法参数是否合法   先定义两个注解类ValidateGroup 和 ValidateFiled ValidateGroup .java package com.zf.an ...

  6. Java获取方法参数名、Spring SpEL解析

    @Test public void testParse() { //表达式解析 ExpressionParser expressionParser = new SpelExpressionParser ...

  7. 如何在 Spring/Spring Boot 中做参数校验?你需要了解的都在这里!

    本文为作者原创,如需转载请在文首著名地址,公众号转载请申请开白. springboot-guide : 适合新手入门以及有经验的开发人员查阅的 Spring Boot 教程(业余时间维护中,欢迎一起维 ...

  8. 如何在 Spring/Spring Boot 中做参数校验

    数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据. 本文结合自己在项目 ...

  9. Spring5.0源码学习系列之Spring AOP简述

    前言介绍 附录:Spring源码学习专栏 在前面章节的学习中,我们对Spring框架的IOC实现源码有了一定的了解,接着本文继续学习Springframework一个核心的技术点AOP技术. 在学习S ...

随机推荐

  1. set常见操作:

    (1)sadd 向一个集合中添加一个元素.例如:sadd set1 Hello (2)smembers 查看集合中的所有元素.例如:smembers set1 (3)srem 删除集合中一个指定的元素 ...

  2. GITHUB的初次使用

          对于一个从未用过  接触过github的人来说,达到一个最终的成功真可谓是历经千辛万苦.在这里真的感谢我们的小组组长,我遇到的问题除了自己的查到的,剩 下的基本上都是组长帮我解决的.当所有 ...

  3. Swift 实现iOS Animation动画教程

    这是一篇翻译文章.原文出处:http://www.raywenderlich.com/95910/uiview-animation-swift-tutorial 动画( animation)是iOS用 ...

  4. Nginx SSL配置过程

    1. 在godaddy购买了UCC SSL(最多5个域名)的SSL证书 2. 设置证书 -- 管理 -- 3. 需要制作证书申请CSR文件(在线工具制作或者openssl命令制作),保存CSR和key ...

  5. String性能优化

    String 使用的优化建议 其他 String 使用的优化建议 以上我们描述了在我们的大量文本分析案例中调用 String 的 subString方法导致内存消耗的问题,下面再列举一些其他将导致内存 ...

  6. 提示错误#165 too few argument in function call

    调用函数时,参数个数少于函数定义.检查一下函数定义和参数调用,两个要一致.

  7. log4j之NDC、MDC

     NDC 介绍 NDC(Nested Diagnostic Context)是 Neil Harrison 在名为<Patterns for Logging Diagnostic Message ...

  8. Java中的blank final

    Java allows the creation of blank finals, which are fields that are declared as final but are not gi ...

  9. Ubuntu安装samba的问题

    问题: root@ubuntu:~# apt-get install samba 正在读取软件包列表... 完成 正在分析软件包的依赖关系树 正在读取状态信息... 完成 有一些软件包无法被安装.如果 ...

  10. HDU 4349 Xiao Ming's Hope

    有这样一个性质:C(n,m)%p=C(p1,q1)*C(p2,q2).......%p,其中pkpk-1...p1,qkqk-1...q1分别是n,m在p进制下的组成. 就完了. #include&l ...