SpringBoot拦截器 SpringBoot拦截器的使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot拦截器 SpringBoot拦截器的使用

久曲键   2021-11-15 我要评论
想了解SpringBoot拦截器的使用的相关内容吗,久曲键在本文为您仔细讲解SpringBoot拦截器的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:SpringBoot拦截器的使用,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框架
  • 过滤器不用注入其它类,拦截器可注入其它类,基于这一点,建议能用拦截器的都用拦截器

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们