`
panqili2120
  • 浏览: 87965 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

SpringMVC中@ResponseBody对UTF-8的支持

阅读更多

 

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

 

于是解决方案:

 

------------------------------------------------------------------------------------------------------------------------

1. 皱眉修改源码, org.springframework.http.converter.StringHttpMessageConverter中第一行代码是这样的,所以你懂得...

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

 

 

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

 

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

 

<!--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>

 

 

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics