You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
test/src/main/java/com/jiudian/manage/config/CustomMVCConfiguration.java

50 lines
2.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.jiudian.manage.config;
//// 导入Spring相关注解和类是核心组件
import org.springframework.context.annotation.Bean;//spring对象
import org.springframework.context.annotation.Configuration;//注释组件
import org.springframework.http.converter.HttpMessageConverter;//负责 HTTP 请求 / 响应消息转换的组件
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;//配置内容协商(如根据请求头确定返回数据格式)
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;// Spring MVC 的配置适配器组件,用于定制 Web 层的行为(如消息转换、拦截器、视图解析等
import java.nio.charset.Charset;//Java 标准库中处理字符集的类
import java.util.List;//Java 集合框架中的列表接口,用于存储转换器集合。
// * 自定义MVC配置类
// * 用于配置HTTP消息转换和内容协商解决中文乱码问题
// */
//Spring 会执行这些方法,将返回的对象存入容器(即 “注册 Bean”供其他组件依赖注入
@Configuration //标识当前类是配置类Spring 会扫描并加载其中的配置。
public class CustomMVCConfiguration extends WebMvcConfigurerAdapter {
//创建并配置String类型的HTTP消息转换器
@Bean
// 声明这是一个Bean会被Spring容器管理
// 创建字符串消息转换器处理响应体中字符串转换设置字符集为UTF-8
public HttpMessageConverter<String> responseBodyConverter(){
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
return converter;//返回创建的转换器对象,交给 Spring 容器管理。
}
@Override//重写父类,自定义消息转换器配置
//HttpMessageConverter<?>:这是 Spring 框架中定义的HTTP 消息转换器接口
// ,其中 <?> 是泛型通配符,表示该转换器可以处理任意类型的数据。
//List<HttpMessageConverter<?>> converters 表示:一个包含多种 HTTP 消息转换器的列表
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
// 先调用父类方法,保留默认的转换器配置
converters.add(responseBodyConverter());
// 添加我们自定义的字符串转换器
}
@Override
//重写了父类WebMvcConfigurerAdapter中的同名方法用于自定义 Spring MVC 的内容协商配置
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}
// 禁用基于URL路径扩展名,不能有后缀的内容协商
// 例如:/api/users.json 或 /api/users.xml 这样的URL将不再生效