>>分享流行的Java框架以及开源软件,对孙卫琴的《精通Spring:Java Web开发技术详解》提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 19788 个阅读者 刷新本主题
 * 贴子主题:  Spring的方法拦截器范例 回复文章 点赞(0)  收藏  
作者:flybird    发表时间:2024-04-07 00:07:30     消息  查看  搜索  好友  邮件  复制  引用

使用到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)    // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
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>

程序猿的技术大观园:www.javathinker.net
网站系统异常


系统异常信息
Request URL: http://www.javathinker.net/WEB-INF/lybbs/jsp/topic.jsp?postID=3508&replyID=0&skin=1&saveSkin=true&pages=1&replyNum=

java.lang.NullPointerException

如果你不知道错误发生的原因,请把上面完整的信息提交给本站管理人员