WebMvcConfigurer配置HandlerInterceptor拦截器失效

2023-05-16

1.前言

Springboot2.0之前,实现拦截器功能的配置类是通过继承(extends)WebMvcConfigurerAdapter类完成的,最近项目把Springboot升级到了Springboot2.X,WebMvcConfigurerAdapter类已经不能使用了,查了资料说现在要通过实现(implements)WebMvcConfigurer接口来完成该功能。

这时候出现问题了,实现(implements)WebMvcConfigurer接口后,启动程序,程序运行过程中根本没走到该配置类和拦截器代码。

2.配置类WebMvcConfig

import com.xq.plugin.SecurityHandlerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

	@Autowired
	SecurityHandlerInterceptor securityHandlerInterceptor;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(securityHandlerInterceptor).addPathPatterns("/**");
	}
}

3.拦截器SecurityHandlerInterceptor

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

@Component
public class SecurityHandlerInterceptor implements HandlerInterceptor {
	private static final Log log = LogFactory.getLog(SecurityHandlerInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HandlerMethod handlerMethod = null;
		if (handler instanceof HandlerMethod) {
			handlerMethod = (HandlerMethod) handler;
		}
		if (handlerMethod == null) {
			return true;
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
		if (log.isDebugEnabled()) {
			log.debug(SecurityHandlerInterceptor.class.getSimpleName() + "postHandle方法");
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug(SecurityHandlerInterceptor.class.getSimpleName() + "afterCompletion方法");
		}
	}

}

 4.失效原因

原来SpringBoot做了这个限制,只有当WebMvcConfigurationSupport类不存在的时候才会生效WebMvc自动化配置,因为我在写swagger配置类时继承(extends)了WebMvcConfigurationSupport类,所以实现(implements)了WebMvcConfigurer接口的WebMvcConfig配置类没有生效。

原swagger配置类代码:

import com.xq.common.constants.AppConstants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config extends WebMvcConfigurationSupport {
    //因为swagger与静态文件访问配置冲突,所以整合swagger需要
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        // springboot 集成swagger2.2后静态资源404,添加如下两行配置
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("xq")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xq.yexiong.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(AppConstants.app+"的API接口")
                .version("1.0")
                .build();
    }

}

5.解决方法

解决方法很简单,就是让swagger配置类不再继承(extends)WebMvcConfigurationSupport类,也去实现(implements)WebMvcConfigurer接口即可。

新swagger配置类代码:

import com.xq.common.constants.AppConstants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config implements WebMvcConfigurer {
    //因为swagger与静态文件访问配置冲突,所以整合swagger需要
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        // springboot 集成swagger2.2后静态资源404,添加如下两行配置
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        //super.addResourceHandlers(registry);
    }

    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("xq")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xq.yexiong.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(AppConstants.app+"的API接口")
                .version("1.0")
                .build();
    }

}

6.总结

springBoot2.0以上 WebMvcConfigurerAdapter 方法过时,有两种替代方案:
1、继承WebMvcConfigurationSupport
2、实现WebMvcConfigurer
但是继承(extends)WebMvcConfigurationSupport类会让Springboot对WebMvc自动化配置失效。所以项目中不能同时使用。

参考文档:https://www.cnblogs.com/sueyyyy/p/11611676.html


  

  
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WebMvcConfigurer配置HandlerInterceptor拦截器失效 的相关文章

  • Tcl/Expect中利用exec调用管道"|"和awk的注意事项

    Tcl Expect中利用exec调用稍微复杂的shell命令时 xff0c 经常会遇到一些小问题 xff0c 常见的就是pipeline 和awk Tcl Expect调用多个shell命令并使用 将其串接在一起时 xff0c 需要注意的
  • pycharm中使用jupyter使用

    步骤 1 安装Jupyter pip install jupyter 2 新建一个IPython文件 3 在Terminal里启动Jupyter Notebook 2 编写程序 随便写点什么测试一下 xff0c 应该得到的结果是这样的 xf
  • ojdbc6 No plugin found for prefix install in the current project解决方案

    原文 xff1a No plugin found for prefix install in the current project解决方案 一滴水的眼泪 CSDN博客 执行下边命令 xff1a mvn install install fi
  • Shell命令

    shell命令 xff1a 操作系统的一个字符串操作 1 关机 xff1a halt reboot xff08 重启 xff09 poweroff 查看或匹配网卡 xff1a ifconfig 帮助手册 man 清屏 xff1a clear
  • 1.20——golang环境配置(在Mac OS上)【没用过】

    本节主要为大家讲解如何在Mac OS上安装Go语言开发包 xff0c 大家可以在Go语言官网下载对应版本的的安装包 xff08 https golang google cn dl xff09 xff0c 如下 图所示 安装Go语言开发包 M
  • spring自动装配Bean的五种方式

    no xff1a 默认方式 xff0c 手动装配方式 xff0c 需要通过ref设定bean的依赖关系byName xff1a 根据bean的名字进行装配 xff0c 当一个bean的名称和其他bean的属性一致 xff0c 则自动装配by
  • ZCU106的FMC接口AD/DA(全网唯一、全网最详)

    马上就要毕业啦 xff0c 好久没写文章了 xff0c 今天给大家带来硕士期间的最后一次AD DA实验的实验记录 xff0c 废话少说 xff0c 先看连接与视频 连接 视频 我做的实验是AN108 43 FL9613的DA与AD回环测试
  • BigDecimalUtils BigDecimal加减乘除

    span class token keyword public span span class token keyword class span span class token class name BigDecimalUtil span
  • 关于引用的疑问

    1 变量名回顾 变量 是一段实际连续存储空间的别名 程序中通过变量 来申请并命名存储空间 通过变量 的名字可以使用存储空间 问题 xff1a 一段连续的存储空间只能有一个别名吗 xff1f 2 c 43 43 中引用 引用 可以看作一个已定
  • 在Ubuntu系统中安装字体(以安装华文行楷和方正舒体为例)

    背景 xff1a 笔者在做一个项目时 xff0c 因为项目是在windows系统中开发的 xff0c 用react写的页面 xff0c 在windows本地验证是没有问题 xff0c 但是部署到服务器 xff08 服务器系统为Ubuntu
  • Linux Shared Memory的查看与设置

    1 Linux Check Memory Usage 2 How to Check Shared Memory on Linux 3 Shared Memory Configuration 共享内存就是进程之间可以共享的一段内存 xff0c
  • java构造和生成固定的json格式(geojson为例)

    java构造和生成json格式 xff08 geojson为例 xff09 一 所要构造的json格式 二 思路和步骤 1 题外说明 本文是先解析读入的txt文件 xff0c 然后建立对应的java类来接受解析的某些值 xff0c 用了自己
  • Android 程序退出 Toast还一直显示 解决方案

    今天 xff0c 改了个bug xff1a 点击两次返回程序退出 如大家所想 xff0c 第一次点击用Toast提示 xff0c 如果在两秒内再次点击那么程序退出 在我们平时写App的时候 xff0c 习惯用Application的上下文对
  • 在word中快速查找所有图片

    选择导航窗格 点击搜索框里的小三角 选择查找图形
  • systemctl命令详解

    在linux内核启动完以后 xff0c 会执行 etc rc d rc local脚本 xff0c 最后再执行 bin login程序 xff0c 进入用户登陆界面 传统的做法 xff0c 如果要在linux里添加开机自启的命令 xff0c
  • Linux系统之下开启tomcat控制台,查看代码运行情况

    方法 xff1a 进入tomcat安装文件夹 xff0c 打开命令行 如下操作 xff1a bin gt startup sh cd logs tail f catalina out
  • 四元数姿态表示总结

    文章目录 简介用法一 xff1a 欧拉角 四元数1 Euler2Quat xff1a 2 Euler 2 Vect 2 Quat xff1a 3 Quat 2 Euler xff1a 用法二 xff1a 旋转矩阵 四元数1 Quat 2 R

随机推荐

  • 调用OpenCV库出现: undefined reference to `xxxxx‘ 的解决办法(使用MinGW编译器)

    记录OpenCV正确安装与调用过程 我的CMakeLists txt如下 xff1a cmake minimum required span class token punctuation span VERSION span class t
  • 解决git fatal:无法找到‘https‘的远程助手

    解决git fatal 无法找到 https 的远程助手 1 问题 今天使用git拉去代码的时候出现 fatal 无法找到 39 https 39 的远程助手错误 xff0c 如下所示 span class token function g
  • [Android Framework]Android 11系统Update-API时Lint检查问题解决和记录

    1 什么是Lint检查 Android Lint 是 ADT 16 xff08 和工具 16 xff09 中引入的一个新工具 xff0c 用于扫描 Android 项目源以查找潜在的错误 Android11之前 xff0c 我们在进行Fra
  • openEuler22.03LTS网卡配置

    VmWare完成安装openEuler xff0c 修改网卡配置文件 xff0c 重启network报错service not found xff0c 因为欧拉使用nmcli管理网络 按照centos7的经验 xff0c 修改ifcfg配置
  • 利用在线词典批量查询英语单词

    进来遇到很多英语生词 xff0c 工具书上给的解释错误百出 xff0c 而很多在线词典不但可以给出某个单词的解释 xff0c 而且有大量的示例 xff0c 因此猜想利用在线词典批量查询这些单词 怎么实现呢 xff1f 首要问题是如何自动获取
  • linux svn服务器搭建 centos 搭建svn服务器

    本文是在CentOS中采用yum安装方式 优点 xff1a 简单 xff0c 一键安装 xff0c 不用手动配置环境变量等 缺点 xff1a 安装位置为yum默认 xff0c 比如我们公司服务器上安装软件有自己的规定 xff0c 一般会采用
  • Firewall 防火墙常用命令

    Firewall开启常见端口命令 xff1a 注意 permanent意思是 永久生效 firewall cmd zone 61 public add port 61 80 tcp permanent firewall cmd zone 6
  • 第二章——keil5修改工程名字

    第一章 stm32f103建立工程 第二章 keil5修改工程名字 目录 1 修改模板文件名 2 修改工程文件名 3 删除中间文件 4 修改输出中间变量文件名 5 点击编译 xff0c 改名成功 1 修改模板文件名 把第一章建立的工程模板的
  • origin2021如何切换中文界面

    origin2021如何切换中文界面 一 直接设置Change Language二 Change Language菜单是灰色的 一 直接设置Change Language 1 单击 Help gt Change Language 2 将La
  • fbe 业务流程分析

    参考链接 xff1a https www cnblogs com bobfly1984 p 14090078 html 总结 根据 data unencrypted key和 data misc vold user keys de 0 路径
  • js的字符串匹配方法match()和Java的字符串匹配方法matches()的使用?以换行符替换为其他字符为例

    js的字符串匹配方法match 和Java的字符串匹配方法matches 的使用 xff1f 以换行符替换为其他字符为例 js的 xff1a str match n igm length会返回str中有多少个换行str match bc i
  • UNIX 环境高级编程

    与你共享 xff0c 与你共舞 xff01 UNIX环境高级编程 xff08 第3版 xff09 是被誉为UNIX编程 圣经 xff1b 书中除了介绍UNIX文件和目录 标准I O库 系统数据文件和信息 进程环境 进程控制 进程关系 信号
  • 华为服务器WebBios创建磁盘阵列

    步骤 1 启动服务器按ctrl 43 h进入WebBios 2 点击Start确定进入下一步 3 左栏的Configuration Wizard添加raid 4 选New Configuration新建raid即可 5 选中硬盘 然后再按N
  • goland 无法编译输出 Compilation finished with exit code 0

    golang编写程序无法输出
  • 分享关于AI的那些事儿

    机器人很厉害 给人治病的ibm 的Watson 沃森 击败世界围棋冠军的AlphaGo阿尔法狗 陪你聊天的机器人 数据标注 木马识别 恶意访问拦截 智能家居 但是17年首次出现了机器人获得国籍 这个机器人叫做索菲亚 这是一个类似人类的机器人
  • String Evolver, My First Genetic Algorithm

    When reading Evolutionary Computation for Modeling and Optimization 1 I found following problem in section 1 2 3 A strin
  • MongoDB特点及功能介绍

    一 MongoDB 介绍 1 基本概念 MongoDB是一个高性能 xff0c 开源 xff0c 无模式的文档型数据库 xff0c 是当前NoSQL数据库产品中最热门的一种 它在许多场景下可用于替代传统的关系型数据库或键 值存储方式 xff
  • 线程同步以及线程调度相关的方法

    wait xff1a 使一个线程处于等待 xff08 阻塞 xff09 状态 xff0c 并且释放所持有的对象的锁 xff1b sleep xff1a 使一个正在运行的线程处于睡眠状态 xff0c 是一个静态方法 xff0c 调用此方法要处
  • 智能医疗辅助诊断——调查与思考

    背景 为什么要做智能医疗 xff1f 优质医疗资源不足且增长缓慢各地方医疗资源分配不均客观条件满足 xff0c 人工智能技术发展 xff0c 算法 算力 数据齐备 目录 指出 xff0c 医用软件按照预期用途分为辅助诊断类和治疗类 诊断功能
  • WebMvcConfigurer配置HandlerInterceptor拦截器失效

    1 前言 Springboot2 0之前 xff0c 实现拦截器功能的配置类是通过继承 extends WebMvcConfigurerAdapter类完成的 xff0c 最近项目把Springboot升级到了Springboot2 X x