spring boot 中文亂碼問題


在剛接觸spring boot 2.0的時候,遇到了一些中文亂碼的問題,網上找了一些解決方法。

這里自己做個匯總。

在application.properties文件中添加:

1 spring.http.encoding.force=true
2 spring.http.encoding.charset=UTF-8
3 spring.http.encoding.enabled=true
4 server.tomcat.uri-encoding=UTF-8

有如上配置后,攔截器中返回的中文已經不亂碼了,但是controller中返回的數據依舊亂碼。

需要在@RequestMapping(這一類定義請求路徑的注解)中增加produces="text/plain;charset=UTF-8"

但是這樣就得要限定請求的數據類型,並且需要在每個請求里都加上這個,工作比較繁雜。

可以自己寫一個配置文件類,繼承WebMvcConfigurationSupport,代碼如下:

 1 @Configuration
 2 public class CustomMVCConfiguration extends WebMvcConfigurationSupport{
 3 
 4     @Bean
 5     public HttpMessageConverter<String> responseBodyConverter() {
 6         StringHttpMessageConverter converter = new StringHttpMessageConverter(
 7                 Charset.forName("UTF-8"));
 8         return converter;
 9     }
10 
11     @Override
12     public void configureMessageConverters(
13             List<HttpMessageConverter<?>> converters) {
14         super.configureMessageConverters(converters);
15         converters.add(responseBodyConverter());
16     }
17 
18     @Override
19     public void configureContentNegotiation(
20             ContentNegotiationConfigurer configurer) {
21         configurer.favorPathExtension(false);
22     }
23 }

基本上就解決了亂碼問題。

如果出現org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.util.LinkedHashMap

就需要在配置類中,添加一些代碼,完整的代碼如下:

 1 @Configuration
 2 public class InterceptorConfig extends WebMvcConfigurationSupport {
 3 
 4     /**
 5      * 解決中文亂碼問題
 6      */
 7     @Bean
 8     public HttpMessageConverter<String> responseBodyConverter() {
 9         return new StringHttpMessageConverter(Charset.forName("UTF-8"));
10     }
11 
12     @Bean
13     public ObjectMapper getObjectMapper() {
14         return new ObjectMapper();
15     }
16 
17     @Bean
18     public MappingJackson2HttpMessageConverter messageConverter() {
19         MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
20         converter.setObjectMapper(getObjectMapper());
21         return converter;
22     }
23 
24     @Override
25     public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
26         super.configureMessageConverters(converters);
27         //解決中文亂碼
28         converters.add(responseBodyConverter());
29         //解決 添加解決中文亂碼后 上述配置之后,返回json數據直接報錯 500:no convertter for return value of type
30         converters.add(messageConverter());
31         converters.add(responseBodyConverter());
32     }
33 
34     @Override
35     public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
36         configurer.favorPathExtension(false);
37     }
38 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM