SpringMVC 使用@ResponseBody返回json 中文亂碼
阿新 • • 發佈:2018-04-05
AI ngs target err bstr .html -s 找到 html
有時候我們發現接收的是中文,返回卻是個?。這確實是個蛋疼的問題,Spring中解析字符串的轉換器默認編碼居然是ISO-8859-1
/** * Implementation of {@link HttpMessageConverter} that can read and write strings. * * <p>By default, this converter supports all media types ({@code */*}), * and writes with a {@code Content-Type} of {@code text/plain}. This can be overridden * by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property. * * @author Arjen Poutsma * @since 3.0 */ public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> { public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
既然找到問題了,那就必須想辦法改過來,不同版本的Spring好像方法還不一樣,網上不少說的都是Spring3.*的,現在Spring4早都出來了
更改方式可以參考
http://stackoverflow.com/questions/3616359/who-sets-response-content-type-in-spring-mvc-responsebody
http://www.cnblogs.com/chenying99/archive/2012/04/17/2453017.html
我現在用的Spring4.2.5,上面說的幾個方法都試了,最後發現只有這兩個可以
方法一,使用(produces = "application/json; charset=utf-8"):
@RequestMapping(value="/getUsersByPage",produces = "application/json; charset=utf-8")
// @RequestMapping("/getUsersByPage")
@ResponseBody
public String getUsersByPage(String page,String rows,String text,HttpServletRequest request,HttpServletResponse response){
方法二,在spring-mvc.xml中添加:(推薦這種)
<!-- 設定消息轉換的編碼為utf-8防止controller返回中文亂碼 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean>
以上兩種方式經過驗證都沒有問題。
SpringMVC 使用@ResponseBody返回json 中文亂碼