原因分析
- 使用ajax从前台页面传输数据到后台controller控制器的时候,出现中文乱码
- 其实乱码问题出现的原因,就是由于默认的tomcat配置,接收请求是以ISO-8859-1来转码,导致中文出现了乱码问题,只要能正确的以utf-8来转码,则可以解决乱码问题。
- 普通数据传输,从jsp页面传到后台controller,中文乱码问题解决方案
- 首先检查jsp页面编码格式是否是utf-8
- 设置中文过滤
<filter>
<filter-name>characterEncodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- springMvc配置文件中设置JSON数据转换
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 注解请求映射
默认是ISO-88859-1,避免乱码这里设置为UTF-8 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8" />
</bean>
<!-- 启动JSON格式的配置,自动将格式转换成JSON格式,不需要其他类 -->
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
解决方案
@ResponseBody
@RequestMapping(value="/getJsonDataByCityName",produces="application/json")
public String getJsonByName(HttpServletRequest request,HttpServletResponse response,@RequestParam String city_name)throws ServletException, IOException
{
//response.setContentType("text/html;charset=UTF-8");
//request.setCharacterEncoding("UTF-8");//解决post乱码问题
System.out.println(request.getCharacterEncoding());
city_name = new String(city_name.getBytes("ISO-8859-1"), "UTF-8");
System.out.println("city_name:"+city_name);
}
- 方式二:
- 配置tomcat目录下的service.xml文件
- tomcat7/conf/server.xml
- 给该行代码加上 URIEncoding="UTF-8" 的编码属性
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8" />