SpringBoot,在做全局異常處理的時候,返回中文字符串時,出現亂碼情況,網上查閱資料之后,解決方式如下所示,自定義WebConfiguration繼承WebMvcConfigurationSupport類(用的是SpringBoot2.0)。
(之前返回json串時遇到亂碼問題,是在@RequestMapping中添加了 produces=“application/json;charset=utf-8”。 但是在處理全局異常信息是,沒有@RequestMapping這個注解去添加該屬性(也許是我學的太淺,還沒找到吧),而且這中做法還限制了請求的數據類型。於是繼續尋找合適的方法,最終找到此解決方案)
1 import java.nio.charset.Charset; 2 import java.util.List; 3 4 import org.springframework.context.annotation.Bean; 5 import org.springframework.context.annotation.Configuration; 6 import org.springframework.http.converter.HttpMessageConverter; 7 import org.springframework.http.converter.StringHttpMessageConverter; 8 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; 9 import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; 10 11 import com.fasterxml.jackson.databind.ObjectMapper; 12 13 import ch.qos.logback.classic.pattern.MessageConverter; 14 15 /** 16 * 解決頁面返回的中文亂碼。 17 * 自定義消息轉換器:自定義WebConfiguration繼承WebMvcConfigurationSupport類 18 * @author Administrator 19 * @date 2018年10月18日上午12:34:22 20 */ 21 @Configuration 22 public class WebConfiguration extends WebMvcConfigurationSupport{ 23 24 //1.這個為解決中文亂碼 25 @Bean 26 public HttpMessageConverter<String> responseBodyConverter() { 27 StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8")); 28 return converter; 29 } 30 31 32 //2.1:解決中文亂碼后,返回json時可能會出現No converter found for return value of type: xxxx 33 //或這個:Could not find acceptable representation 34 //解決此問題如下 35 public ObjectMapper getObjectMapper() { 36 return new ObjectMapper(); 37 } 38 39 //2.2:解決No converter found for return value of type: xxxx 40 public MappingJackson2HttpMessageConverter messageConverter() { 41 MappingJackson2HttpMessageConverter converter=new MappingJackson2HttpMessageConverter(); 42 converter.setObjectMapper(getObjectMapper()); 43 return converter; 44 } 45 46 47 48 @Override 49 public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { 50 super.configureMessageConverters(converters); 51 //解決中文亂碼 52 converters.add(responseBodyConverter()); 53 54 //解決: 添加解決中文亂碼后的配置之后,返回json數據直接報錯 500:no convertter for return value of type 55 //或這個:Could not find acceptable representation 56 converters.add(messageConverter()); 57 } 58 59 }