寻找写代码感觉(九)之SpringBoot拦截器的使用

一、拦截器简介

拦截器通常通过动态代理的方式来执行。
拦截器的生命周期由IoC容器管理,可以通过注入等方式来获取其他Bean的实例,使用更方便。

二、拦截器配置使用方式

1、过滤器拦截器作用范围

2、拦截器的使用

示例代码如下:

 package com.rongrong.wiki.interceptor;

 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
 import org.springframework.web.servlet.HandlerInterceptor;
 import org.springframework.web.servlet.ModelAndView;

 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 /**
  * 拦截器:Spring框架特有的,常用于登录校验,权限校验,请求日志打印 /login
  */
 @Component
 public class LogInterceptor implements HandlerInterceptor {

     private static final Logger LOG = LoggerFactory.getLogger(LogInterceptor.class);

     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         // 打印请求信息
         LOG.info("------------- LogInterceptor 开始 -------------");
         LOG.info("请求地址: {} {}", request.getRequestURL().toString(), request.getMethod());
         LOG.info("远程地址: {}", request.getRemoteAddr());

         long startTime = System.currentTimeMillis();
         request.setAttribute("requestStartTime", startTime);
         return true;
     }

     @Override
     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
         long startTime = (Long) request.getAttribute("requestStartTime");
         LOG.info("------------- LogInterceptor 结束 耗时:{} ms -------------", System.currentTimeMillis() - startTime);
     }
 }

将拦截器加入到配置中,示例代码如下:

package com.rongrong.wiki.config;

import com.rongrong.wiki.interceptor.LogInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {

    @Resource
    LogInterceptor loginInterceptor;

    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login");
    }
}

重新编译启动,查看结果如下:

三、知识点总结

1、拦截器的使用

  • 返回true会往后执行
  • 返回false会结束,可以利用这点来做权限拦截
  • addPathPatterns(),要拦截请求
  • excludePathPatterns(),排除请求,不拦截

2、拦截器和过滤器的相同与不同

  • 都可以用来统一处理请求,比如:打印日志、权限控制
  • 过滤器依赖于servlet容器,拦截器依赖Spring框架
  • 过滤器不用注入其它类,拦截器可注入其它类,基于这一点,建议能用拦截器的都用拦截器

到此,SpringBoot拦截器的使用介绍完,有兴趣的同学请自行尝试!

优秀不够,你是否无可替代

软件测试交流QQ群:721256703,期待你的加入!!

欢迎关注我的微信公众号:软件测试君


原文地址:https://www.cnblogs.com/longronglang/p/15470625.html