1、使用ajax从前台页面传输数据到后台controller控制器的时候,出现中文乱码(问号???)。
之前在网上找了各种解决方案,都行不通,最后发现是tomcat服务器接收数据的问题
解决方案:
方式一:在controller接收参数时,对参数进行转码
1
2
3
4
5
6
7
8
9
10
11
|
@ResponseBody 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" 的编码属性
1
2
3
|
< Connector port = "8080" protocol = "HTTP/1.1" connectionTimeout = "20000" redirectPort = "8443" URIEncoding = "UTF-8" /> |
原因分析:
其实乱码问题出现的原因,就是由于默认的tomcat配置,接收请求是以ISO-8859-1来转码,导致中文出现了乱码问题,只要能正确的以utf-8来转码,则可以解决乱码问题。
2、普通数据传输,从jsp页面传到后台controller,中文乱码问题解决方案
(1)、首先检查jsp页面编码格式是否是utf-8
(2)、设置中文过滤
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<!-- 中文编码 --> < 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 > |
(3)、springMvc配置文件中设置JSON数据转换
1
2
3
4
5
6
7
8
9
10
11
12
13
|
< 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 > |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://my.oschina.net/shxjinchao/blog/1614756