SpringMVC 中文乱码解决方案

来源:互联网 发布:奥利奥爆浆油条淘宝 编辑:程序博客网 时间:2024/06/14 03:33

SpringMVC 中文乱码解决方案

首先了解源码

/** * Implementation of {@link HttpMessageConverter} that can read and write strings. * * <p>By default, this converter supports all media types ({@code &#42;&#47;&#42;}), * 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;

关键点:

  1. 源码默认的编码是ISO-8859-1:public static final Charset DEFAULT_CHARSET = Charset.forName(“ISO-8859-1”);

  2. 修改方式: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")@ResponseBodypublic String testUTF8(HttpServletRequest request,HttpServletResponse response){..........}