spring自定義注解實現(xiàn)攔截器的實現(xiàn)方法
類似用戶權(quán)限的需求,有些操作需要登錄,有些操作不需要,可以使用過濾器filter,但在此使用過濾器比較死板,如果用的話,就必須在配置文件里加上所有方法,而且 不好使用通配符。這里可以采用一種比較簡單靈活的方式,是采用spring 的 methodInterceptor攔截器完成的,并且是基于注解的。大概是用法是這樣的:
@LoginRequired
@RequestMapping(value = "/comment")
public void comment(HttpServletRequest req, HttpServletResponse res) {
// doSomething,,,,,,,,
}
這里是在Spring mvc 的controller層的方法上攔截的,注意上面的@LoginRequired 是自定義的注解。這樣的話,該方法被攔截后,如果有該注解,則表明該 方法需要用戶登錄后才能執(zhí)行某種操作,于是,我們可以判斷request里的session或者Cookie是否包含用戶已經(jīng)登錄的身份,然后判斷是否執(zhí)行該方法;如果沒有,則執(zhí)行另一種操作。
下面是自定義注解的代碼:
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
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();
}
}
配置文件:
<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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java實現(xiàn)猜數(shù)字小游戲(有次數(shù)限制)
這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)猜數(shù)字小游戲,有次數(shù)限制,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-05-05
Springboot整合Dubbo教程之項目創(chuàng)建和環(huán)境搭建
本篇文章主要介紹了Springboot整合Dubbo教程之項目創(chuàng)建和環(huán)境搭建,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12
Java實現(xiàn)漢字轉(zhuǎn)全拼音的方法總結(jié)
在軟件開發(fā)中,經(jīng)常會遇到需要將漢字轉(zhuǎn)換成拼音的場景,比如在搜索引擎優(yōu)化、數(shù)據(jù)存儲、國際化等方面,Java作為一種廣泛使用的編程語言,提供了多種方法來實現(xiàn)漢字到拼音的轉(zhuǎn)換,本文將詳細(xì)介紹幾種常用的Java漢字轉(zhuǎn)全拼音的方法,并提供具體的代碼示例和步驟2024-12-12
Springboot中@RequestParam和@PathVariable的用法與區(qū)別詳解
這篇文章主要介紹了Springboot中@RequestParam和@PathVariable的用法與區(qū)別詳解,RESTful API設(shè)計的最佳實踐是使用路徑參數(shù)來標(biāo)識一個或多個特定資源,而使用查詢參數(shù)來對這些資源進(jìn)行排序/過濾,需要的朋友可以參考下2024-01-01

