WebMvcConfigurer 介绍

embedded/2025/2/23 4:18:50/

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/embedded/163664.html

相关文章

新型基于Go语言的恶意软件利用Telegram作为C2通信渠道

研究人员发现了一种新型后门恶意软件&#xff0c;使用Go语言编写&#xff0c;并利用Telegram作为其命令与控制&#xff08;C2&#xff09;通信渠道。尽管该恶意软件似乎仍处于开发阶段&#xff0c;但它已经具备完整的功能&#xff0c;能够执行多种恶意活动。这种创新的C2通信方…

电脑ip如何手动切换?多种方法详解‌

在数字化时代&#xff0c;IP地址作为网络设备的唯一标识&#xff0c;扮演着至关重要的角色。无论是出于隐私保护、访问特定资源&#xff0c;还是出现网络冲突等&#xff0c;掌握如何手动切换电脑的IP地址都显得尤为重要。本文将详细介绍多种切换电脑IP地址的方法&#xff0c;希…

DeepSeek预测25考研分数线

25考研分数马上要出了。 目前&#xff0c;多所大学已经陆续给出了分数查分时间&#xff0c;综合往年情况来看&#xff0c;每年的查分时间一般集中在2月底。 等待出成绩的日子&#xff0c;学子们的心情是万分焦急&#xff0c;小编用最近爆火的“活人感”十足的DeepSeek帮大家预…

Redis 全方位解析:从入门到实战

引言 在当今互联网快速发展的时代&#xff0c;高并发、低延迟的应用场景越来越普遍。Redis&#xff0c;作为一款高性能的开源数据库&#xff0c;以其卓越的性能和灵活的功能&#xff0c;成为了许多开发者的首选工具。无论是在缓存、消息队列&#xff0c;还是在实时数据分析等领…

Java零基础入门笔记:(4)方法

前言 本笔记是学习狂神的java教程&#xff0c;建议配合视频&#xff0c;学习体验更佳。 【狂神说Java】Java零基础学习视频通俗易懂_哔哩哔哩_bilibili 第1-2章&#xff1a;Java零基础入门笔记&#xff1a;(1-2)入门&#xff08;简介、基础知识&#xff09;-CSDN博客 第3章…

接口自动化框架篇:Pytest中的接口请求封装!

在进行接口自动化测试时&#xff0c;我们需要一个稳定、易用且可扩展的框架来封装接口请求。Pytest是一种非常流行的Python测试框架&#xff0c;它提供了很多方便的功能和插件&#xff0c;可以帮助我们轻松进行接口自动化测试。 接口请求封装是框架的核心部分&#xff0c;它负…

华为昇腾920b服务器部署DeepSeek翻车现场

最近到祸一台HUAWEI Kunpeng 920 5250&#xff0c;先看看配置。之前是部署的讯飞大模型&#xff0c;发现资源利用率太低了。把5台减少到3台&#xff0c;就出了他 硬件配置信息 基本硬件信息 按照惯例先来看看配置。一共3块盘&#xff0c;500G的系统盘&#xff0c; 2块3T固态…

自制操作系统第三天

sunshineguest 今天要干什么&#xff1f; 继续开发制作启动区Makefile入门 一&#xff1a; 对原有的helloos.nas进行了再次开发&#xff0c;其中用到了一些新的指令&#xff1a; 1:“MOV AX,0”,相当于”AX0;”这样一个赋值语句。同样&#xff0c;”MOV SS,AX”就相当于”…