類似用戶權(quán)限的需求,有些操作需要登錄,有些操作不需要,可以使用過濾器filter,但在此使用過濾器比較死板,如果用的話,就必須在配置文件里加上所有方法,而且 不好使用通配符。這里可以采用一種比較簡單靈活的方式,是采用spring 的 methodInterceptor攔截器完成的,并且是基于注解的。大概是用法是這樣的:
1
2
3
4
5
|
@LoginRequired @RequestMapping (value = "/comment" ) public void comment(HttpServletRequest req, HttpServletResponse res) { // doSomething,,,,,,,, } |
這里是在Spring mvc 的controller層的方法上攔截的,注意上面的@LoginRequired 是自定義的注解。這樣的話,該方法被攔截后,如果有該注解,則表明該 方法需要用戶登錄后才能執(zhí)行某種操作,于是,我們可以判斷request里的session或者Cookie是否包含用戶已經(jīng)登錄的身份,然后判斷是否執(zhí)行該方法;如果沒有,則執(zhí)行另一種操作。
下面是自定義注解的代碼:
1
2
3
4
5
6
7
8
9
10
|
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 { } |
下面是自定義的方法攔截器,繼續(xù)自aop的MethodInterceptor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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-------------------------" ); } //執(zhí)行被攔截的方法,切記,如果此方法不調(diào)用,則被攔截的方法不會被執(zhí)行。 return mi.proceed(); } } |
配置文件:
1
2
3
4
5
6
7
|
< 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 > |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.jianshu.com/p/86dca4aa78a3