• Spring MVC拦截器学习


    1 介绍

    Spring Web MVC是基于Servlet API构建的原始Web框架。

    2 拦截器

    2.1 定义

    springmvc框架的一种拦截机制

    2.2 使用

    2.2.1 两步走

    1. 实现HandlerInterceptor接口
    2. 注册(xml或者注解 )
    2.2.2 HandlerInterceptor接口

    uWlpI1.png

    1. 实现HandlerInterceptor接口
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class InterceptorTest implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("preHandle");
            return true; // 只有返回true才会继续向下执行,返回false取消当前请求
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            System.out.println("postHandle");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            System.out.println("afterCompletion");
        }
    }
    
    1. 注册
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    /**
     * 注册拦截器(扫描到拦截器)
     */
    @Configuration
    public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new InterceptorTest()).addPathPatterns("/**");
            super.addInterceptors(registry);
        }
    }
    
    1. 使用场景

    拦截器可以在请求前后进行数据拦截,类似门岗,门岗一般都有检查身份功能,对于拦截器来说,拦截器有权限校验功能,把握请求是否可以通过,可以在里面进行token检验或者其他。

    性能检测。可以在请求前后进行时间计算,检测接口性能。

    日记记录。拦截请求数据,记录请求参数。

  • 相关阅读:
    数论笔记
    哈哈哈
    闭关修炼屯题中,期末考完A
    acm几何
    POJ
    Educational Codeforces Round 42 (Rated for Div. 2) D.Merge Equals (优先队列)
    Educational Codeforces Round 42 (Rated for Div. 2) C. Make a Square (dfs)
    牛客网 VVQ 与线段 (优先队列或线段树或RMQ)
    Educational Codeforces Round 41 (Rated for Div. 2) C.Chessboard (DP)
    Educational Codeforces Round 41 (Rated for Div. 2)D. Pair Of Lines
  • 原文地址:https://www.cnblogs.com/chenzhuantou/p/11665447.html
Copyright © 2020-2023  润新知