`
maven26
  • 浏览: 2003 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

spring3 mvc @ResponseBody 中文乱码解决方案

阅读更多

最近俺的项目中使用spring3 mvc,前端使用jquery,感觉真是爽啊,尤其是采用注解后感觉整体的结构清晰,

配置很少,能够快速的开发应用,真是做到开发,约定俗称了。

但是在使用@ResponseBody 时,遇到了编码的问题,俺正统用的utf-8,结果前台竟然是乱码,只好baidu+google啦。

在网上浏览了好多,大家各显其能,有的自己写Converter,有的改response编码。大部分兄弟们都是采用的bean注入方式来设定编码。下面是个网上的例子

http://tdcq.iteye.com/blog/842222

 

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<property name="messageConverters">
<list>
<bean class = "org.springframework.http.converter.StringHttpMessageConverter">
<property name = "supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>

<mvc:annotation-driven />

 

上面这段代码,我试了,发现偶尔起作用,大部分时间不起作用。去掉<mvc:annotation-driven />后起作用了,但是可能其他代码会受到影响。

 

随后俺跟随断点,看看到底是咋走的?俺通过StackTrace看到,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter

这个类中存在supportedMediaTypes,这个类的supportedMediaTypes一直都是iso-8859-1,根本不是俺想注入的utf-8,俺当时就想啦,那俺注入这里面不就行啦!

俺尝试如下:

 

<bean
  class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
  <property name="messageConverters">
   <list>
    <ref bean="stringHttpMessageConverter" />
   </list>
  </property>
 </bean>
 <bean id="stringHttpMessageConverter"
  class="org.springframework.http.converter.StringHttpMessageConverter">
  <property name="supportedMediaTypes">
   <list>
    <value>text/plain;charset=UTF-8</value>
   </list>
  </property>
 </bean>

一试,竟然成功了。随后俺跟了跟断点起作用了。

这里奉劝各位兄弟姐妹,网上的东西还是要仔细研究的,不要转来转去的。

 

 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics