引起乱码原因为spring mvc使用的默认处理字符串编码为ISO-8859-1,具体参考org.springframework.http.converter.StringHttpMessageConverter类中public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
解决方法:
第一种方法:
对于需要返回字符串的方法添加注解,如下:
@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);
}
此方法只针对单个调用方法起作用。
第二种方法:
在配置文件中加入
<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>
本文详细介绍了Spring MVC中乱码问题的根源在于使用了ISO-8859-1编码,提供了两种解决方案:一种是在单个方法上使用注解进行特定处理;另一种是全局配置更改,以确保所有响应都使用UTF-8编码。

10000

被折叠的 条评论
为什么被折叠?



