直击解决方案:
在SpringBoot项目中的自定义MVC配置类中进行修改 (我自己实现的 MVC配置类是: MvcConfiguration ,继承了 WebMvcConfigurer, ApplicationContextAware,关系到中文乱码的是 WebMvcConfigurer 这个类下面的 StringHttpMessageConverter
- 在 MvcConfiguration 类中添加以下代码:
@Bean
public HttpMessageConverter<String> responseBodyStringConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
return converter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
converters.add(responseBodyStringConverter());
}
- 如果不懂,献上我的整个MvcConfiguration类代码:
@Configuration
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer, ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean(name = "viewResolver")
public ViewResolver createViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setApplicationContext(this.applicationContext);
viewResolver.setCache(false);
viewResolver.setPrefix("/WEB-INF/html/");
viewResolver.setSuffix(".html");
return viewResolver;
}
@Bean(name = "multipartResolver")
public CommonsMultipartResolver createMultipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setDefaultEncoding("utf-8");
multipartResolver.setMaxUploadSize(20971520);
multipartResolver.setMaxInMemorySize(20971520);
return multipartResolver;
}
@Bean
public HttpMessageConverter<String> responseBodyStringConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
return converter;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
converters.add(responseBodyStringConverter());
}
}
关于 StringHttpMessageConverter,这里有篇大佬的文章讲解:点击进入