SpringBoot 中文乱码
先添加fastjson依赖包,在重写方法 configureMessageConverters(List<HttpMessageConverter<?>> converters)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
@Configuration
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
/* 解决中文乱码 RestController */
@SuppressWarnings("serial")
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// for string
// 普通输出中文 使用utf-8
converters.add(new StringHttpMessageConverter(Charset.forName("utf-8")));
// for json
// 普通输出中文 使用utf-8
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
fastConverter.setSupportedMediaTypes(new ArrayList<MediaType>() {
{
add(MediaType.APPLICATION_JSON_UTF8);
}
});
// 支持 输出 数组 对象 结果格式化美化 额外 输出 屏蔽 null值
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
}
SpringMVC 中文乱码
解决中文乱码response
response.setContentType(“text/html;charset=UTF-8”);
(HandlerInterceptor preHandle 定义拦截器这样无需每次手段设置)
response.getWriter()
解决中文乱码ResponseBody
@RestController @ResponseBody
// produces = “application/json; charset=utf-8”
(xml配置,这样无需每次手动设置)
< mvc:annotation-driven >
< !– 消息转换器 –>
< mvc:message-converters register-defaults=”true”>
< bean class=”org.springframework.http.converter.StringHttpMessageConverter”>
< property name=”supportedMediaTypes” value=”text/html;charset=UTF-8”/>
< /mvc:message-converters>
< /mvc:annotation-driven>
xxx.jsp乱码
<%@ page contentType=”text/html;charset=UTF-8” language=”java” %>