在使用spring mvc responseBody注解的时候,返回的数据往往会是乱码,这是因为spring mvc

   默认对http请求

使用iso8859-1对字符编码;


public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

解决的方法:

重写StringHttpMessageConverter


/**
 *
 * @description:http请求设置转码
 * @author:sunla
 * @date:2013-7-8下午04:42:03
 */
public class GBKStringHttpMessageConverter extends StringHttpMessageConverter {
    private static final MediaType GBK = new MediaType("application", "xml",
            Charset.forName("gbk"));//查看源码可知MediaType的构造方法
    private boolean writeAcceptCharset = true;
    @Override
    protected MediaType getDefaultContentType(String dumy) {
        return GBK;
    }
    protected List<Charset> getAcceptedCharsets() {
        return Arrays.asList(GBK.getCharSet());
    }
    protected void writeInternal(String s, HttpOutputMessage outputMessage)
            throws IOException {
        if (this.writeAcceptCharset) {
            outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
        }
        Charset charset = GBK.getCharSet();
        FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(),
                charset));
    }
    public boolean isWriteAcceptCharset() {
        return writeAcceptCharset;
    }
    public void setWriteAcceptCharset(boolean writeAcceptCharset) {
        this.writeAcceptCharset = writeAcceptCharset;
    }
}

在xml中添加(mvc:annotation-driven 之前)

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean id="GBKStringHttpMessageConverter" class="com.*.support.GBKStringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
<!--可添加多个accpet type-->                       <value>application/xml</value>
                        <value>text/plain</value>
                    </list>
                </property>
            </bean>
<!--spring mvc 对于json的支持-->
            <ref bean="jsonHttpMessageConverter"/>
        </list>
    </property>
</bean>
                                                                                           
    <mvc:annotation-driven/>

如果在http请求中带有中文参数,可以在tomcat(类似的应用服务器中) servet.xml中加入URIEncoding

<Connector port="8080" URIEncoding="gbk" useBodyEncodingForURI="true"
                          protocol="HTTP/1.1"
              connectionTimeout="20000"
              redirectPort="8443" />

这是在java中对字符就该

String str=new String("str".getByte("iso8859-1"),"gbk");

就能得到中文了