引發亂碼緣由爲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