WebMvcConfigurer 介绍

ops/2025/2/23 4:09:34/

WebMvcConfigurer 介绍

  • 1. 什么是WebMvcConfigurer 介绍
  • 2. WebMvcConfigurer接口常用的方法
  • 3. 使用WebMvcConfigurer实现跨域
  • 4. 使用WebMvcConfigurer配置拦截器
  • 5. 使用WebMvcConfigurer配置静态资源
    • 5.1 配置外部目录(本地文件系统)详细解释
  • 6. 使用 WebMvcConfigurer 配置视图解析
    • 6.1 详细说明
      • 6.1.1 使用 WebMvcConfigurer 配置 Thymeleaf 视图解析
  • 7. 使用 WebMvcConfigurer 配置消息转换器

1. 什么是WebMvcConfigurer 介绍

WebMvcConfigurer 是 Spring Boot 中用于扩展 Spring MVC 功能的接口,可以用来自定义 Web 相关的配置,例如:

✅ 跨域(CORS) 配置 addCorsMappings
✅ 拦截器(Interceptor) addInterceptors
✅ 静态资源映射 addResourceHandlers
✅ 消息转换器(Message Converter) configureMessageConverters
✅ 视图解析器(View Resolver) configureViewResolvers
✅ 参数解析

它的主要作用是在不改变 Spring Boot 默认行为的情况下,提供灵活的扩展能力。


复杂的解释: WebMvcConfigurer配置类其实是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter。基于java-based方式的spring mvc配置,需要创建一个配置类并实现WebMvcConfigurer 接口;

在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加自定义拦截器,消息转换器等。SpringBoot 2.0 后,该类被标记为@Deprecated(弃用)。官方推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport。

2. WebMvcConfigurer接口常用的方法

java"> /* 拦截器配置 */
void addInterceptors(InterceptorRegistry var1);/* 视图跳转控制器 */
void addViewControllers(ViewControllerRegistry registry);/** 静态资源处理 **/
void addResourceHandlers(ResourceHandlerRegistry registry);/* 默认静态资源处理器 */
void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);/** 这里配置视图解析器 **/
void configureViewResolvers(ViewResolverRegistry registry);/* 配置内容裁决的一些选项 */
void configureContentNegotiation(ContentNegotiationConfigurer configurer);/** 解决跨域问题 **/
public void addCorsMappings(CorsRegistry registry) ;

3. 使用WebMvcConfigurer实现跨域

java">import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class CorsConfig {@Beanpublic WebMvcConfigurer corsConfigurer() {return new WebMvcConfigurer() {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") // 允许所有路径.allowedOrigins("https://frontend.com") // 允许特定域名.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的请求方法.allowedHeaders("*") // 允许所有请求头.allowCredentials(true) // 允许携带 Cookie.maxAge(3600); // 预检请求的缓存时间}};}
}

当然Nginx也可以实现

location / {proxy_pass http://localhost:8080;add_header 'Access-Control-Allow-Origin' 'https://frontend.com';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';add_header 'Access-Control-Allow-Credentials' 'true';if ($request_method = OPTIONS) {return 204;}
}

a. 其中location / 其中/代表匹配所有请求。

b. proxy_pass http://localhost:8080; Nginx 会把所有匹配 / 的请求转发到 http://localhost:8080(假设 Spring Boot 运行在 8080 端口)。 这样前端请求 Nginx,Nginx 代理请求到 Spring Boot,对外隐藏后端服务。

c. add_header 'Access-Control-Allow-Origin' 'https://frontend.com';
允许跨域的前端来源
允许 https://frontend.com 访问后端 API。
如果改成'*'add_header 'Access-Control-Allow-Origin' '*'; 表示所有域都可以访问:

d. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE'; 允许前端调用 GET、POST、OPTIONS、PUT、DELETE 方法。

e. add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
允许前端在请求中携带 Authorization(比如 Bearer Token)和 Content-Type 头。

f. add_header 'Access-Control-Allow-Credentials' 'true';
🔹 允许携带 Cookie
允许前端发送带有 Cookie 的跨域请求(如身份验证)。
⚠️ 如果启用 Access-Control-Allow-Credentials,必须指定具体的 Access-Control-Allow-Origin,不能用 *。

g.

java">if ($request_method = OPTIONS) {return 204;
}

🔹 处理预检请求(OPTIONS)

当浏览器发送 OPTIONS 预检请求(比如跨域的 POST 请求),Nginx 直接返回 204 No Content,避免 Spring Boot 处理这类请求,提高性能。

总结

  1. 将请求转发到 Spring Boot (http://localhost:8080)
  2. 允许 https://frontend.com 访问后端 API
  3. 支持跨域(CORS):
  4. 允许 GET, POST, OPTIONS, PUT, DELETE 请求
  5. 允许 Authorization 和 Content-Type 请求头
  6. 允许前端携带 Cookie
  7. 优化预检请求(OPTIONS),直接返回 204,减少后端负担

📌 适用场景
✅ 前后端分离项目(前端 https://frontend.com,后端 http://localhost:8080)
✅ 使用 Nginx 代理后端 API,同时处理跨域
✅ 后端 API 需要支持身份验证(携带 Cookie 或 Token)

4. 使用WebMvcConfigurer配置拦截器

拦截器(HandlerInterceptor)可以用于日志记录、权限校验、请求处理等

java">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 WebConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyInterceptor()).addPathPatterns("/api/**") // 只拦截 /api/ 开头的请求.excludePathPatterns("/api/login", "/api/register"); // 这些路径不拦截}
}

✅ 适用场景:

  • 用户登录拦截
  • 请求日志记录
  • 权限控制

5. 使用WebMvcConfigurer配置静态资源

java">import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {// 将 /static/ 目录下的资源映射到 /resources/** 访问路径registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/static/");// 访问 http://localhost:8080/images/test.jpg 时,会去 D:/uploads/ 目录查找registry.addResourceHandler("/images/**").addResourceLocations("file:D:/uploads/");// 访问 http://localhost:8080/files/doc.pdf 时,会去 /home/user/docs/ 目录查找registry.addResourceHandler("/files/**").addResourceLocations("file:/home/user/docs/");}
}

说明

  1. @Configuration:标记该类为 Spring 配置类,使其生效。
  2. 实现 WebMvcConfigurer 接口:
    通过 addResourceHandlers 方法自定义静态资源映射规则。
  3. registry.addResourceHandler("/resources/**"):
    访问路径形如 /resources/** 的请求,会被映射到 classpath:/static/目录下的资源(即 src/main/resources/static/)。
    例如,src/main/resources/static/css/style.css 可以通过 http://localhost:8080/resources/css/style.css 访问。
  4. 配置外部目录(本地文件系统):
    /images/** 访问路径映射到 D:/uploads/ 目录(必须加 file: 前缀)。
    /files/** 访问 /home/user/docs/ 目录下的资源。

默认静态资源位置
如果没有自定义 WebMvcConfigurer,Spring Boot 默认会从以下位置加载静态资源:

  • classpath:/static/

  • classpath:/public/

  • classpath:/resources/

  • classpath:/META-INF/resources/
    例如:

  • src/main/resources/static/index.html 可以直接通过 http://localhost:8080/index.html 访问。
    但如果自定义了 WebMvcConfigurer,默认配置可能会被覆盖,因此需要手动添加 addResourceHandlers 方法来保持默认行为。

5.1 配置外部目录(本地文件系统)详细解释

在 Spring Boot 中,默认的静态资源(如 CSS、JS、图片等)通常存放在 src/main/resources/static/ 目录下,并且可以直接通过 http://localhost:8080/资源路径 访问。

但是,如果你想让应用访问 本地文件系统(比如 D:/uploads/ 或 /home/user/docs/),就需要手动配置 addResourceHandlers(),并使用 file: 前缀 指定外部目录。

示例 1:Windows 配置外部目录

java">@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {// 让 /images/** 访问 D:/uploads/ 目录下的资源registry.addResourceHandler("/images/**").addResourceLocations("file:D:/uploads/");
}

解释

  • addResourceHandler(“/images/**”):
    • 表示访问 http://localhost:8080/images/xxx.jpg 时,会去 D:/uploads/ 目录查找 xxx.jpg。
  • addResourceLocations(“file:D:/uploads/”):
    • file: 必须加上,表明这是一个文件系统路径,而不是类路径(classpath)。
    • 这个目录是 Windows 本地磁盘,不是 Spring Boot 默认的 static/ 目录。
  • 示例
    • D:/uploads/test.jpg 可以通过 http://localhost:8080/images/test.jpg 访问。

示例2:同时支持多个目录

java">@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/uploads/**").addResourceLocations("file:D:/uploads/", "file:/home/user/docs/");
}

这样访问 http://localhost:8080/uploads/test.jpg 时,Spring 会先去 D:/uploads/ 目录找,再去 /home/user/docs/ 目录找。

6. 使用 WebMvcConfigurer 配置视图解析

WebMvcConfigurer 还可以用于配置自定义视图解析器。

java">import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;@Configuration
public class WebConfig implements WebMvcConfigurer {@Beanpublic ViewResolver viewResolver() {InternalResourceViewResolver resolver = new InternalResourceViewResolver();resolver.setPrefix("/WEB-INF/views/"); // 视图文件前缀resolver.setSuffix(".jsp"); // 视图文件后缀return resolver;}
}

✅ 适用场景:

  • Spring MVC + JSP
  • Thymeleaf 或 FreeMarker 视图解析

6.1 详细说明

在 Spring Boot 中,视图解析器(View Resolver) 负责将控制器返回的视图名称解析为实际的 视图文件(如 HTML、JSP、Thymeleaf 等)。如果你想自定义视图解析规则,可以实现 WebMvcConfigurer 接口。

6.1.1 使用 WebMvcConfigurer 配置 Thymeleaf 视图解析

Spring Boot 默认集成了 Thymeleaf 作为模板引擎,我们可以使用 WebMvcConfigurer 进行自定义配置,比如:

  • 修改视图文件存放路径
  • 自定义前缀/后缀
java">import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void configureViewResolvers(ViewResolverRegistry registry) {// 配置 Thymeleaf 视图解析器registry.jsp("/WEB-INF/views/", ".jsp");  // 仅用于 JSP}
}

解释

  • registry.jsp("/WEB-INF/views/", ".jsp")
  • 前缀:/WEB-INF/views/
  • 后缀:.jsp
  • 例如:当控制器返回 “home”,最终视图路径解析为 /WEB-INF/views/home.jsp。
    注意:
    这个registry.jsp() 主要用于 JSP 视图解析,如果使用 Thymeleaf,Spring Boot 会自动管理,无需额外配置。

7. 使用 WebMvcConfigurer 配置消息转换器

Spring Boot 提供了默认的 JSON 处理方式(Jackson),但如果你想使用 Gson 或自定义格式,可以在 WebMvcConfigurer 里配置消息转换器。

java">import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.List;@Configuration
public class WebConfig implements WebMvcConfigurer {@Beanpublic Gson gson() {return new GsonBuilder().setPrettyPrinting().create();}@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(new GsonHttpMessageConverter(gson()));}
}

✅ 适用场景:

  • 替换默认的 Jackson 为 Gson
  • 支持自定义 JSON 格式

http://www.ppmy.cn/ops/159763.html

相关文章

高电服务器托管:企业IT基础设施的可靠之选

高电服务器托管服务&#xff0c;是指企业将自身高耗电的服务器设备或算力服务器设备交由专业托管公司进行管理和维护的一种服务模式。托管公司提供包括安全机房环境、网络设备、系统软件以及专业技术人员等全方位支持&#xff0c;使企业能够专注于核心业务的开发和运营。 高电…

详解AbstractQueuedSynchronizer(AQS)源码

引言 上篇文章讲解了CountDownLatch源码&#xff0c;底层是继承了AQS基类调用父类和重写父类方法实现的&#xff0c;本文将简介AQS源码和架构设计&#xff0c;帮助我们更深入理解多线程实战。 源码架构 1. 状态变量 state AQS 使用一个 int 类型的变量 state 来表示同步状态…

A与B组件自动对齐与组装,无映射直接补偿。

网上针对组装的从视觉到控制动作,要不就是收费,要不就是简单介绍。这么详细的比较难找~ 手下留情,不喜勿喷! Show time~ 分步解决方案: 标定阶段(Calibration) 9点张氏标定(每个位置A1、A2、B1、B2): 使用机械手在相机视野内沿Z字形路径移动,覆盖9个点(XY方…

CTF-内核pwn入门1: linux内核模块基础原理

本文由A5rZ在2025-2-18-21:00编写 1.可加载内核模块是什么&#xff1f; 内核可加载模块&#xff08;*.ko 文件&#xff09;是内核的一种扩展机制&#xff0c;可以在不重启系统的情况下加载和卸载代码。它们允许动态地向内核添加新的功能或支持。 以下是一些内核模块常见的功能&…

[qt5学习笔记]Application Example示例程序源码解析

开发环境问题 vs2022下直接打开ui、ts文件失败 解决办法如下图&#xff0c; 设置designer独立运行。估计是嵌入运行存在些许bug。 同理&#xff0c;ts编辑工具linguist也存在这个问题。 qrc rc的编辑嵌入编辑都正常&#xff0c;但分离式更稳定可靠。 qt creator编译失败 原…

在华为云部署应用,通过阿里云代理调用第三方接口的利弊与解决方案

以下是一篇针对“在华为云上部署应用,通过阿里云代理服务器调用第三方接口”所做的问答与分析整理而成的博文示例,供您发布或分享。内容涵盖了方案现状、主要弊端以及详细的优化与解决思路。 在华为云部署应用,通过阿里云代理调用第三方接口的利弊与解决方案 一、背景介绍 …

华为固态电池引发的思索

华为固态电池真牛&#xff01; 超长续航&#xff1a;单次充电即可行驶3000公里 极速充电&#xff1a;五分钟内充满80% 极致安全&#xff1a;不可燃、不漏液 长寿命设计&#xff1a;循环寿命达10000次以上 如上是华为电池展示的优势项&#xff0c;每一条都让我们心动不已。…

CPP集群聊天服务器开发实践(四):客户端开发与功能测试

目录 1 总体思想 2 关键部分的实现 1. TCP连接过程 2. 登录过程 3. 聊天主菜单页面 4. 完整源代码 3 功能测试 客户端&#xff08;client&#xff09;开发主要是以命令行的形式与服务器进行交互&#xff0c;无需人工输入json消息&#xff0c;以此来验证登录注册注销、添…