天天看點

spring 攔截器 spring自定義注解

從别人處轉載 找不到出處

最近項目裡加上了使用者權限,有些操作需要登入,有些操作不需要,之前做項目做權限,喜歡使用過濾器,但在此使用過濾器比較死闆,如果用的話,就必須在配置檔案裡加上所有方法,而且 不好使用通配符。是以想了想,之前在人人用過的一種比較簡單靈活的權限判斷,是采用spring 的 methhodInterceptor攔截器完成的,并且是基于注解的。

現在自己寫了一套。大概是用法是這樣的:

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

我是在Spring mvc 的controller層的方法上攔截的,注意上面的@LoginRequired 是我自定義的注解。這樣的話,該方法被攔截後,如果有該 注解,則表明該 方法需要使用者登入後才能執行某種操作,于是乎,我們可以判斷request裡的session或者Cookie是否包含使用者已經登入的身份,然後判斷是否執行該方法;如果沒有,則執行另一種操作。

下面是自定義注解的代碼:

package com.qunar.wireless.ugc.controllor.web;  

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;  
import com.qunar.wireless.ugc.controllor.web.LoginRequired;  


/** 
 * @author tao.zhang 
 * @create-time 2012-2-31 
 */  
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>