引发乱码缘由为spring mvc使用的默认处理字符串编码为ISO-8859-1,具体参考org.springframework.http.converter.StringHttpMessageConverter类中public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");spring
解决方法:json
第一种方法:spring-mvc
对于须要返回字符串的方法添加注解,以下:mvc
@RequestMapping(value="/getUsers", produces = "application/json; charset=utf-8")
public String getAllUser() throws JsonGenerationException, JsonMappingException, IOException
{
List<User> users = userService.getAll();
ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(users));
DataGrid dg = new DataGrid();
dg.setData(users);
return om.writeValueAsString(dg);
}app
此方法只针对单个调用方法起做用。编码
第二种方法:spa
在配置文件中加入utf-8
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>字符串
参考:http://stackoverflow.com/questions/3616359/who-sets-response-content-type-in-spring-mvc-responsebodyget