解决Spring MVC @ResponseBody出现问号乱码问题

原因是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

猜你喜欢

转载自www.cnblogs.com/runtimeexception/p/10025530.html