加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

springmvc 发送ajax出现中文乱码的解决方法汇总

发布时间:2020-12-15 23:08:14 所属栏目:百科 来源:网络整理
导读:使用spingmvc,在JS里面通过ajax发送请求,并返回json格式的数据,从数据库拿出来是正确的中文格式,展示在页面上就是错误的??,研究了一下,有几种解决办法。 我使用的是sping-web-3.2.2,jar 方法一: 在@RequestMapping里面加入produces = "text/html;ch

使用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出现中文乱码问题小编就给大家介绍到这里,希望对大家有所帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读