解决方法有以下三种:
一、在web.xml中添加过滤器:(这种方法大多数情况下能用,bz的用这种方法行不通,有大佬明白的可以指点一下)
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
二、在Controller中的方法的注解中添加 produces="text/html;charset=UTF-8" :
//根据id查询用户信息
@RequestMapping(value="/select"/*,produces="text/html;charset=UTF-8"*/)
@ResponseBody
public String select(int id) {
JSONObject json = new JSONObject();
//调用service
User user = null;
try {
user = userService.selectById(id);
} catch (Exception e) {
e.printStackTrace();
}
if (user!=null) {
json.put("user", user);
}else {
json.put("user", "User is not found");
}
return json.toJSONString();
}
三、在SpringMVC的配置文件springmvc.xml中添加注解如下代码(此方法是永久的、可一劳永逸的方法,添加后即可避免重复使用第二种方法,使代码更简洁):
<!-- 注解驱动 作用:会自动的注册一些bean,包括RequestMappingHandler和RequestMappingHandlerAdapter
还提供了数据绑定的支持、json数据传输的支持等 -->
<!--自定义消息转换器的编码,解决后台传输json回前台时,中文乱码问题-->
<mvc:annotation-driven >
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter" >
<property name = "supportedMediaTypes">
<list>
<value>application/json;charset=utf-8</value>
<value>text/html;charset=utf-8</value>
<!-- application 可以在任意 form 表单里面 enctype 属性默认找到-->
<value>application/x-www-form-urlencoded</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" ></bean>
</mvc:message-converters>
</mvc:annotation-driven>
总结:以上仅为bz知道的三种方法,如有大神知道更好的方法,请不吝赐教