---
title: "【转】Spring 使用 @ResponseBody 返回中文乱码问题解决"
author: "grefr"
date: "2014-06-13T15:43:30Z"
tags: []
categories: ["开源软件"]
slug: "spring-responsebody"
draft: false
lastmod: "2015-06-23T11:32:40Z"
id: 2079477
url: "https://grefr.iteye.com/blog/2079477"
---

详见： [http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt102](http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt102)

 

今天在使用spring 的时候，发现中文返回的是乱码。

经过研究发现，主要是@ResponseBody 引起的。主要是由于 @ResponseBody 返回字符串结果的时候，使用了org.springframework.http.converter.StringHttpMessageConverter 中默认的编码。

请看 org.springframework.http.converter.StringHttpMessageConverter ：

 

**\[java]** [view plain](http://blog.csdn.net/initphp/article/details/8813601 "view plain")[copy](http://blog.csdn.net/initphp/article/details/8813601 "copy")[print](http://blog.csdn.net/initphp/article/details/8813601 "print")[?](http://blog.csdn.net/initphp/article/details/8813601 "?")

 

1. public class StringHttpMessageConverter extends AbstractHttpMessageConverter&lt;String&gt; {
2. public static final Charset DEFAULT\_CHARSET = Charset.forName("ISO-8859-1");
3. private final List&lt;Charset&gt; availableCharsets;
4. private boolean writeAcceptCharset = true;
5. public StringHttpMessageConverter() {
6. super(new MediaType("text", "plain", DEFAULT\_CHARSET), MediaType.ALL);
7. this.availableCharsets = new ArrayList&lt;Charset&gt;(Charset.availableCharsets().values());
8. }

 

默认情况下，是ISO-8859-1编码，我们要将ISO-8859-1编码改成utf-8编码。

 

**\[java]** [view plain](http://blog.csdn.net/initphp/article/details/8813601 "view plain")[copy](http://blog.csdn.net/initphp/article/details/8813601 "copy")[print](http://blog.csdn.net/initphp/article/details/8813601 "print")[?](http://blog.csdn.net/initphp/article/details/8813601 "?")

 

1. public static final Charset DEFAULT\_CHARSET = Charset.forName("ISO-8859-1");

我们的解决方法是，在spring-servlet.xml中，加入一个bean

 

 

**\[html]** [view plain](http://blog.csdn.net/initphp/article/details/8813601 "view plain")[copy](http://blog.csdn.net/initphp/article/details/8813601 "copy")[print](http://blog.csdn.net/initphp/article/details/8813601 "print")[?](http://blog.csdn.net/initphp/article/details/8813601 "?")

 

01. &lt;bean
02. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt;
03. &lt;property name="messageConverters"&gt;
04. &lt;list&gt;
05. &lt;bean
06. class="org.springframework.http.converter.StringHttpMessageConverter"&gt;
07. &lt;property name="supportedMediaTypes"&gt;
08. &lt;list&gt;
09. &lt;bean class="org.springframework.http.MediaType"&gt;
10. &lt;constructor-arg index="0" value="text" /&gt;
11. &lt;constructor-arg index="1" value="plain" /&gt;
12. &lt;constructor-arg index="2" value="UTF-8" /&gt;
13. &lt;/bean&gt;
14. &lt;/list&gt;
15. &lt;/property&gt;
16. &lt;/bean&gt;
17. &lt;/list&gt;
18. &lt;/property&gt;
19. &lt;/bean&gt;