欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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 &#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")
@ResponseBody
public String testUTF8(HttpServletRequest request,HttpServletResponse response){
..........
}