java拦截器的实现方法,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();

}

}

配置文件:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值