1. 程式人生 > >spring 攔截器 MethodInterceptor 配置 config aop

spring 攔截器 MethodInterceptor 配置 config aop

最近專案里加上了使用者許可權,有些操作需要登入,有些操作不需要,之前做專案做許可權,喜歡使用過濾器,但在此使用過濾器比較死板,如果用的話,就必須在配置檔案里加上所有方法,而且 不好使用萬用字元。所以想了想,之前在人人用過的一種比較簡單靈活的許可權判斷,是採用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>