---
title: "SpringMVC中@ResponseBody对UTF-8的支持"
author: "panqili2120"
date: "2013-04-09T16:21:07Z"
tags: ["J2EE", "Java", "Spring", "spring mvc"]
categories: ["编程语言"]
slug: "springmvc-responsebody-utf-8"
draft: false
lastmod: "2013-04-09T16:22:27Z"
id: 1844565
url: "https://liqipan.iteye.com/blog/1844565"
---

由于org.springframework.http.converter.StringHttpMessageConverter中默认的编码为**ISO-8859-1**，而在使用@ResponseBody时SpringMVC会通过这个类对输出的内容进行编码，所以Ajax在SpringMVC的项目中会乱码...

 

于是解决方案：

 

\------------------------------------------------------------------------------------------------------------------------

1\. ![皱眉](http://www.iteye.com/javascripts/tinymce/plugins/emotions/img/smiley-frown.gif "皱眉")修改源码， org.springframework.http.converter.StringHttpMessageConverter中第一行代码是这样的，所以你懂得...

```
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
```

 

 

2\. 通过配置Bean进行依赖注入

 

Spring3.1的时候，只有像下面那样才可以正常设置UTF-8。。。注意要放在最上方，&lt;mvc:annotation-driven /&gt;也不能在前面

 

```
<!--Spring3.1推荐使用RequestMappingHandlerAdapter -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="webBindingInitializer">
			<bean class="com.zf.ms.web.MyWebBindingInitializer"></bean>
		</property>
		<property name="messageConverters">
			<list>
				<bean class="org.springframework.http.converter.StringHttpMessageConverter">
					<property name="supportedMediaTypes">
						<list>
							<value>text/html;charset=UTF-8</value>
						</list>
					</property>
				</bean>
			</list>
		</property>
	</bean>
```

 

 

另外还可以这样配置，但我在SpringMVC3.1中试了下，发现不行。。

```
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean id="stringHttpMessageConverter"
                      class="com.zf.ms.util.ConfigurableStringHttpMessageConverter">
                    <constructor-arg value="UTF-8"/>
                </bean>
            </list>
        </property>
    </bean>
```