解决Spring MVC @ResponseBody返回中文字符串乱码问题

来源:互联网 发布:mac 用apple id登陆 编辑:程序博客网 时间:2024/05/16 19:36

引起乱码原因为spring mvc使用的默认处理字符串编码为ISO-8859-1,

具体参考org.springframework.http.converter.StringHttpMessageConverter类中public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

解决方法:

第一种方法:

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

[java] view plain copy
  1. @RequestMapping(value="/loginSubmit.html", produces = "application/json; charset=utf-8")  
  2. @ResponseBody  
  3. public Object toLoginSubmit(HttpServletRequest request,HttpServletResponse response){  
  4.     return "登录成功中文显示";  
  5. }  

此方法只针对单个调用方法起作用。

第二种方法:

在配置文件中加入

[html] view plain copy
  1. <mvc:annotation-driven>  
  2.     <mvc:message-converters register-defaults="true">  
  3.         <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
  4.             <property name="supportedMediaTypes" value = "text/html;charset=UTF-8" />  
  5.         </bean>  
  6.     </mvc:message-converters>  
  7. </mvc:annotation-driven>  

阅读全文
0 0