有时候我们发现接收的是中文,返回却是个?。这确实是个蛋疼的问题,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>
以上两种方式经过验证都没有问题。