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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis實現(xiàn)動態(tài)查詢、模糊查詢功能
這篇文章主要介紹了MyBatis實現(xiàn)動態(tài)查詢、模糊查詢功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06SpringCloud maven-assembly-plugin 多級目錄打包的實現(xiàn)
本文主要介紹了SpringCloud maven-assembly-plugin 多級目錄打包的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10spring boot配置MySQL數(shù)據(jù)庫連接、Hikari連接池和Mybatis的簡單配置方法
這篇文章主要介紹了spring boot配置MySQL數(shù)據(jù)庫連接、Hikari連接池和Mybatis的簡單配置方法,需要的朋友可以參考下2018-03-03