原因是SpringMVC的@ResponseBody使用的默认处理字符串编码为ISO-8859-1,而我们前台或者客户端的编码一般是UTF-8或者GBK。现将解决方法分享如下!

第一种方法:

对于需要返回字符串的方法添加注解,如下:

@RequestMapping(value="/getUser", produces = "application/json; charset=utf-8")
 public String getUser() throws Exception
 {
   User user = new User();
   user.setName("小明");
   user.setHobby("游泳");
   return new Gson().toJson(user);
 }

但是这种解决方法只对单个方法起作用!

第二种方法:
在SpringMVC的配置文件中加入:

<mvc:annotation-driven>
   <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes" value = "text/html;charset=UTF-8" />
    </bean>
   </mvc:message-converters>
</mvc:annotation-driven>

 

text/html

相关文章:

  • 2022-12-23
  • 2021-06-09
  • 2021-05-25
  • 2018-01-25
猜你喜欢
  • 2022-03-01
  • 2021-08-23
  • 2022-01-08
  • 2021-10-24
相关资源
相似解决方案