springmvc ajax放回json中文乱码???

场景:

项目配置了spring encoding filter,前后台编码统一为UTF-8,,Tomcat也改了字符集编码, response 设置字符集无法使用(由于方法返回的是String,并不是response 的write方式

注:

以上转自网络,谢谢雷锋。

本人使用的是第一种方法。(若接口返回的非json格式的String则不能用,会导致前台无法解析)

使用spingmvc,在JS里面通过ajax发送请求,并返回json格式的数据,从数据库拿出来是正确的中文格式,展示在页面上就是错误的??,研究了一下,有几种解决办法。 

  我使用的是sping-web-3.2.2,jar 

  方法一: 

  在@RequestMapping里面加入produces = "text/html;charset=UTF-8" 

Java代码   收藏代码
  1. @RequestMapping(value = "/configrole", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")  
  2. public @ResponseBody String configrole() {  
  3.   ......  
  4. }  



方法二: 

因为在StringHttpMessageConverter里面默认设置了字符集是ISO-8859-1 

所以拿到源代码,修改成UTF-8并打包到spring-web-3.2.2.jar 

Java代码   收藏代码
  1. public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String>  
  2. {  
  3.   public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");  
  4.   ..........  
  5. }  
  6.    



方法三: 

修改org.springframework.http.MediaType它的构造方法的参数,并在applicationContext-mvc.xml 加入配置 

Java代码   收藏代码
  1. public MediaType(String type, String subtype, Charset charset) {  
  2.     super(type, subtype, charset);  
  3. }  



Xml代码   收藏代码
  1. <bean id="stringHttpMessageConverter"  
  2.     class="org.springframework.http.converter.StringHttpMessageConverter">  
  3.     <property name="supportedMediaTypes">  
  4.         <list>  
  5.             <bean class="org.springframework.http.MediaType">  
  6.                 <constructor-arg value="text" />  
  7.                 <constructor-arg value="plain" />  
  8.                 <constructor-arg value="UTF-8" />  
  9.             </bean>  
  10.         </list>  
  11.     </property>  
  12. </bean>  



方法四: 

  直接将org.springframework.http.converter.StringHttpMessageConverter 里面的属性defaultCharset设置成utf-8

Xml代码   收藏代码
  1. <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">  
  2.      <property name="defaultCharset" value="UTF-8"/>  
  3. </bean>  




猜你喜欢

转载自573804039.iteye.com/blog/2312295