spring方法拦截实例

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

简单例子代码如下:

1、定义需要拦截的类

 

 

Java代码  收藏代码
  1. public class LoginAction{  
  2.      
  3.     //没有权限限制  
  4.     @RequestMapping(value = "/login")  
  5.     public void login(HttpServletRequest req, HttpServletResponse res) {  
  6.            //登录功能.  
  7.    }  
  8.   
  9.    //需要登录完成后才可访问  
  10.    @LoginMethod  
  11.    @RequestMapping(value = "/userList")  
  12.     public void userList(HttpServletRequest req, HttpServletResponse res) {  
  13.            //获取用户列表  
  14.    }  
  15.   
  16. }  

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

 

 

2、定义LoginMethod注解

Java代码  收藏代码
  1. @Target(ElementType.METHOD)   //方法
  2. @Retention(RetentionPolicy.RUNTIME)    // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
  3. public @interface LoginMethod {  
  4.      
  5. }  

3、定义MethodInterceptor拦截器

Java代码  收藏代码
  1. public class SystemMethodInterceptor implements MethodInterceptor {  
  2.     @Override  
  3.     public Object invoke(MethodInvocation methodInvocation) throws Throwable {         
  4.         Method method = methodInvocation.getMethod();     
  5.         if(method.isAnnotationPresent(LoginMethod.class)){//加了@LoginMethod注解,被拦截  
  6.              User user = sessionUtil.getCurrUser();  
  7.              if(user == null){//未登录  
  8.                  //proceed方法不调用,方法被拦截  
  9.                  return null;  
  10.              }else{  
  11.                  return methodInvocation.proceed();//该方法不调用,则被拦截的方法不会被执行  
  12.              }  
  13.         }else{  
  14.             return methodInvocation.proceed();  
  15.         }  
  16.     }  
  17. }  

 

4、配置文

Xml代码  收藏代码
  1. <bean id="systemMethodInterceptor" class="com.tzz.interceptor.SystemMethodInterceptor" >  
  2. </bean>  
  3. <aop:config>   
  4. <!--切入点-->   
  5.  <aop:pointcut id="methodPoint" expression="execution(* com.tzz.controllor.web.*.*(..)) "/><!--在该切入点使用自定义拦截器-->   
  6. <aop:advisor pointcut-ref="methodPoint" advice-ref="systemMethodInterceptor"/>  
  7. </aop:config>   
posted @ 2017-07-01 17:50  沧海红心  阅读(762)  评论(0编辑  收藏  举报