最近項目裡加上瞭用戶權限,有些操作需要登錄,有些操作不需要,之前做項目做權限,喜歡使用過濾器,但在此使用過濾器比較死板,如果用的話,就必須在配置文件裡加上所有方法,而且 不好使用通配符。所以想瞭想,之前在人人用過的一種比較簡單靈活的權限判斷,是采用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>
作者:gameover8080