欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

spring自定義注解實(shí)現(xiàn)攔截器的實(shí)現(xiàn)方法

 更新時(shí)間:2017年08月24日 10:27:58   作者:王帥199207  
本篇文章主要介紹了spring自定義注解實(shí)現(xiàn)攔截器的實(shí)現(xiàn)方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

類似用戶權(quán)限的需求,有些操作需要登錄,有些操作不需要,可以使用過(guò)濾器filter,但在此使用過(guò)濾器比較死板,如果用的話,就必須在配置文件里加上所有方法,而且 不好使用通配符。這里可以采用一種比較簡(jiǎn)單靈活的方式,是采用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í)行該方法;如果沒(méi)有,則執(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)用,則被攔截的方法不會(huì)被執(zhí)行。 
      return mi.proceed(); 
    } 
  } 

配置文件:

  <bean id="springMethodInterceptor" class="com.qunar.wireless.ugc.interceptor.LoginRequiredInterceptor1" ></bean> 
  <aop:config> 
    <!--切入點(diǎn)--> 
     <aop:pointcut id="loginPoint" expression="execution(public * com.qunar.wireless.ugc.controllor.web.*.*(..)) "/>  
     <!--在該切入點(diǎn)使用自定義攔截器--> 
     <aop:advisor pointcut-ref="loginPoint" advice-ref="springMethodInterceptor"/> 
  </aop:config>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論