zoukankan      html  css  js  c++  java
  • SpringMVC拦截器的应用

    一、作用

    1. 好文章参考:https://www.cnblogs.com/panxuejun/p/7715917.html
    2. 对请求进行预处理和后处理;
    3. 使用场景:
      • 登录验证,判断用户是否登录
      • 权限验证,判断用户是否有权限访问资源,如校验token
      • 日志记录,记录请求操作日志(用户ip,访问时间等),以便统计请求访问量
      • 处理cookie、本地化、国际化、主题等
      • 性能监控,监控请求处理时长等。

     

    二、实现

    1. 继承HandlerInterceptorAdapter抽象类或者实现HandlerInterceptor接口;
    2. 示例:
    public class InterceptorDemo extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
            StringBuffer requestURL = httpServletRequest.getRequestURL();
            System.out.println("前置拦截器1 preHandle: 请求的uri为:"+requestURL.toString());
            return true;
        }
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
            System.out.println("拦截器1 postHandle: ");
        }
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
            System.out.println("拦截器1 afterCompletion: ");
        }
    }

    四大方法:

    preHandle是在请求controllor前调用,返回true才向后调用其它方法,

    postHandler在调用Controller方法之后、视图渲染之前调用,

    afterCompletion是在渲染视图完成之后使用,

    afterConcurrentHandlingStarted方法用来处理异步请求。

    三、注册

    • 通过@Component 或者 @Configuration将Bean注册到spring容器中
    @Configuration
    public class InterceptorConfig implements WebMvcConfigurer{

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
            //注册TestInterceptor拦截器
            InterceptorRegistration registration = registry.addInterceptor(new InterceptorDemo());
            registration.addPathPatterns("/**");                      //所有路径都被拦截
            registration.excludePathPatterns(                         //添加不拦截路径
                                             "你的登陆路径",            //登录
                                             "/**/*.html",            //html静态资源
                                             "/**/*.js",              //js静态资源
                                             "/**/*.css",             //css静态资源
                                             "/**/*.woff",
                                             "/**/*.ttf"
                                             );    
        }
     }
  • 相关阅读:
    壳的编写(1)-- 简介与搭建框架
    Writing Your Own Packer
    中断门
    记一次:Windows的Socket编程学习和分析过程
    封装调用包含界面的MFC dll
    编译vtk8.1.1 + 在vs2017中配置开发环境
    迁移通知
    基于CAN总线的汽车诊断协议UDS(上位机开发驱动篇)
    基于CAN总线的汽车诊断协议UDS(ECU底层模块移植开发)
    浅谈jQuery,老司机带你jQuery入门到精通
  • 原文地址:https://www.cnblogs.com/flame540/p/13973247.html
Copyright © 2011-2022 走看看