spring方法拦截器 MethodInterceptor 配置

本文介绍如何利用Spring的MethodInterceptor实现权限控制。MethodInterceptor支持注解和通配符,提供了一种灵活的拦截方式。通过定义自定义注解@LoginMethod和拦截器,可以在方法执行前进行必要的权限检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

简单例子代码如下:

1、定义需要拦截的类

 

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注解

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

3、定义MethodInterceptor拦截器

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、配置文

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

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值