SpringMVC 中文乱码解决方案
程序员文章站
2022-05-30 23:38:48
...
SpringMVC 中文乱码解决方案
首先了解源码
/**
* Implementation of {@link HttpMessageConverter} that can read and write strings.
*
* <p>By default, this converter supports all media types ({@code */*}),
* and writes with a {@code Content-Type} of {@code text/plain}. This can be overridden
* by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
private final Charset defaultCharset;
private final List<Charset> availableCharsets;
private boolean writeAcceptCharset = true;
关键点:
源码默认的编码是ISO-8859-1:public static final Charset DEFAULT_CHARSET = Charset.forName(“ISO-8859-1”);
修改方式:by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property
解决方案
1、在spring-servlet.xml中添加
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
2、在代码里写
@RequestMapping(value="/test",produces = "application/json; charset=utf-8")
@ResponseBody
public String testUTF8(HttpServletRequest request,HttpServletResponse response){
..........
}
上一篇: PHP中文乱码解决方案