spring自定义注解实现拦截器

类似用户权限的需求,有些操作需要登录,有些操作不需要,可以使用过滤器filter,但在此使用过滤器比较死板,如果用的话,就必须在配置文件里加上所有方法,而且 不好使用通配符。这里可以采用一种比较简单灵活的方式,是采用spring 的 methodInterceptor拦截器完成的,并且是基于注解的。大概是用法是这样的:

@LoginRequired  
@RequestMapping(value = "/comment")  
public void comment(HttpServletRequest req, HttpServletResponse res) {  
    // doSomething,,,,,,,,  
}  

这里是在Spring mvc 的controller层的方法上拦截的,注意上面的@LoginRequired 是自定义的注解。这样的话,该方法被拦截后,如果有该注解,则表明该 方法需要用户登录后才能执行某种操作,于是,我们可以判断request里的session或者Cookie是否包含用户已经登录的身份,然后判断是否执行该方法;如果没有,则执行另一种操作。


下面是自定义注解的代码:

import java.lang.annotation.ElementType;  
import java.lang.annotation.Retention;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  
  
@Target(ElementType.METHOD)  
@Retention(RetentionPolicy.RUNTIME)  
public @interface LoginRequired  {  
     
}  

下面是自定义的方法拦截器,继续自aop的MethodInterceptor

    import javax.servlet.http.HttpServletRequest;  
    import org.aopalliance.intercept.MethodInterceptor;  
    import org.aopalliance.intercept.MethodInvocation;  
     
    public class LoginRequiredInterceptor1 implements MethodInterceptor {  
      
      
        @Override  
        public Object invoke(MethodInvocation mi) throws Throwable {  
                  
            Object[] ars = mi.getArguments();  
                
            for(Object o :ars){  
                if(o instanceof HttpServletRequest){  
                   System.out.println("------------this is a HttpServletRequest Parameter------------ ");  
                }  
            }  
            // 判断该方法是否加了@LoginRequired 注解  
            if(mi.getMethod().isAnnotationPresent(LoginRequired.class)){  
                 System.out.println("----------this method is added @LoginRequired-------------------------");  
            }  
           //执行被拦截的方法,切记,如果此方法不调用,则被拦截的方法不会被执行。  
            return mi.proceed();  
        }  
    }  

配置文件:

    <bean id="springMethodInterceptor" class="com.qunar.wireless.ugc.interceptor.LoginRequiredInterceptor1" ></bean>  
    <aop:config>  
       <!--切入点-->  
          <aop:pointcut id="loginPoint"  expression="execution(public * com.qunar.wireless.ugc.controllor.web.*.*(..)) "/>   
          <!--在该切入点使用自定义拦截器-->  
          <aop:advisor pointcut-ref="loginPoint" advice-ref="springMethodInterceptor"/>  
    </aop:config>  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,491评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,081评论 6 342
  • 5.2全单第一天,西红柿苹果汁500ml,菠萝苹果汁500ml,水1000ml,啃3节甘蔗,感觉量有点少,或者说喝...
    诚love阅读 1,911评论 0 0
  • 表层习惯完成情况:早起(中)阅读(中)听力(高) 早起比平时晚了半个小时,晚上睡得挺早啊~可能是最近的天气比较适合...
    呀呀呀呀呀dream阅读 903评论 0 0
  • 一、什么是真正的起跑线 有一句话我们听的都有点厌烦了,所以我说起来都要鼓足勇气,但是今天还必须要提到这句话,那就是...
    可可儿妈阅读 8,097评论 0 0