spring方法拦截器 MethodInterceptor

使用到spring方法拦截器 MethodInterceptor实现权限控制,MethodInterceptor可以使用通配符,并且是基于注解的。

简单例子代码如下:

1、定义需要拦截的类


Java代码 收藏代码

public class LoginAction{

//没有权限限制
@RequestMapping(value = "/login")
public void login(HttpServletRequest req, HttpServletResponse res) {
//登录功能.
}

//需要登录完成后才可访问
@LoginMethod
@RequestMapping(value = "/userList")
public void userList(HttpServletRequest req, HttpServletResponse res) {
//获取用户列表
}

}

注意上面的@LoginMethod是我自定义的注解





2、定义LoginMethod注解
Java代码 收藏代码

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginMethod {

}

3、定义MethodInterceptor拦截器
Java代码 收藏代码

public class SystemMethodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Method method = methodInvocation.getMethod();
if(method.isAnnotationPresent(LoginMethod.class)){//加了@LoginMethod注解,被拦截
User user = sessionUtil.getCurrUser();
if(user == null){//未登录
//proceed方法不调用,方法被拦截
return null;
}else{
return methodInvocation.proceed();//该方法不调用,则被拦截的方法不会被执行
}
}else{
return methodInvocation.proceed();
}
}
}



4、配置文
Xml代码 收藏代码

<bean id="systemMethodInterceptor" class="com.tzz.interceptor.SystemMethodInterceptor" >
</bean>
<aop:config>
<!--切入点-->
<aop:pointcut id="methodPoint" expression="execution(* com.tzz.controllor.web.*.*(..)) "/><!--在该切入点使用自定义拦截器-->
<aop:advisor pointcut-ref="methodPoint" advice-ref="systemMethodInterceptor"/>
</aop:config>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值