温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

spring中的拦截器怎么利用注解实现

发布时间:2020-12-02 17:06:34 来源:亿速云 阅读:275 作者:Leah 栏目:编程语言

本篇文章给大家分享的是有关spring中的拦截器怎么利用注解实现,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

类似用户权限的需求,有些操作需要登录,有些操作不需要,可以使用过滤器filter,但在此使用过滤器比较死板,如果用的话,就必须在配置文件里加上所有方法,而且 不好使用通配符。这里可以采用一种比较简单灵活的方式,是采用spring 的 methodInterceptor拦截器完成的,并且是基于注解的。

@LoginRequired 
@RequestMapping(value = "/comment") 
public void comment(HttpServletRequest req, HttpServletResponse res) { 
  // doSomething,,,,,,,, 
} 

这里是在Spring mvc 的controller层的方法上拦截的,注意上面的@LoginRequired 是自定义的注解。这样的话,该方法被拦截后,如果有该注解,则表明该 方法需要用户登录后才能执行某种操作,于是,我们可以判断request里的session或者Cookie是否包含用户已经登录的身份,然后判断是否执行该方法;如果没有,则执行另一种操作。

下面是自定义注解的代码:

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; 
   
  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>

以上就是spring中的拦截器怎么利用注解实现,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI