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

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

  方法一:

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

@RequestMapping(value = "/configrole", method = RequestMethod.GET, produces = "text/html;charset=UTF-8") 
public @ResponseBody String configrole() { 
 ...... 
} 

方法二:

因为在StringHttpMessageConverter里面默认设置了字符集是ISO-8859-1
所以拿到源代码,修改成UTF-8并打包到spring-web-3.2.2.jar

public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> 
{ 
 public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); 
 .......... 
}

方法三:

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

public MediaType(String type, String subtype, Charset charset) { 
  super(type, subtype, charset); 
} 

Xml代码 

<bean id="stringHttpMessageConverter" 
  class="org.springframework.http.converter.StringHttpMessageConverter"> 
  <property name="supportedMediaTypes"> 
    <list> 
      <bean class="org.springframework.http.MediaType"> 
        <constructor-arg value="text" /> 
        <constructor-arg value="plain" /> 
        <constructor-arg value="UTF-8" /> 
      </bean> 
    </list> 
  </property> 
</bean> 

方法4

org.springframework.http.converter.StringHttpMessageConverter类是处理请求或相应字符串的类,并且默认字符集为ISO-8859-1,所以在当返回json中有中文时会出现乱码。

StringHttpMessageConverter的父类里有个List<MediaType> supportedMediaTypes属性,用来存放StringHttpMessageConverter支持需特殊处理的MediaType类型,如果需处理的MediaType类型不在supportedMediaTypes列表中,则采用默认字符集。

解决办法,只需在配置文件中加入如下代码:

<mvc:annotation-driven>
<mvc:message-converters>
 <bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
 <value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

如果需要处理其他 MediaType 类型,可在list标签中加入其他value标签

关于springmvc 发送ajax出现中文乱码问题小编就给大家介绍到这里,希望对大家有所帮助!

点赞(114)

评论列表共有 0 条评论

立即
投稿
返回
顶部