SpringBoot返回页面乱码解决

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 }
原文地址:https://www.cnblogs.com/Jeremy2001/p/11423833.html