POST請求亂碼
原因分析:一般瀏覽器使用編碼默認和操作系統保持一致,而中文操作系統一般默認為gbk,我們的服務為utf-8
解決辦法:在web.xm中配置編碼過濾器
1 <filter>
2 <filter-name>encodingFilter</filter-name>
3 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
4 <init-param>
5 <param-name>encoding</param-name>
6 <param-value>utf-8</param-value>
7 </init-param>
8 <init-param>
9 <param-name>forceEncoding</param-name>
10 <param-value>true</param-value>
11 </init-param>
12 </filter>
13 <filter-mapping>
14 <filter-name>encodingFilter</filter-name>
15 <url-pattern>/*</url-pattern>
16 </filter-mapping>
GET請求亂碼
原因分析:一般tomcat默認認為的url欄和頁面使用的不是同一編碼,其他服務器基本上解決了post亂碼get亂碼也就解決了。
解決辦法:在tomcat中server.xml中的port=“8080”的配置項中,加上一個 URIEncoding=”utf-8屬性
返回亂碼
現象:瀏覽器請求某個使用@ResponseBody返回json的接口,返回json中有中文亂碼。
原因分析:SpringMVC中解析字符串的轉換器默認編碼是ISO-8859-1
解決辦法:
方法1,在Controller中的@RequestMapping注解中配置 produces = "application/json; charset=utf-8",缺點是每個方法都要配。
方法2,在Spring-MVC.xml中配置字符串轉換器取代默認轉換器
1 <!-- 處理請求返回json字符串的中文亂碼問題 -->
2 <mvc:annotation-driven>
3 <mvc:message-converters register-defaults="true">
4 <!-- StringHttpMessageConverter編碼為UTF-8,防止亂碼 -->
5 <bean class="org.springframework.http.converter.StringHttpMessageConverter">
6 <constructor-arg value="UTF-8" />
7 <property name="supportedMediaTypes">
8 <list>
9 <bean class="org.springframework.http.MediaType">
10 <constructor-arg index="0" value="text" />
11 <constructor-arg index="1" value="plain" />
12 <constructor-arg index="2" value="UTF-8" />
13 </bean>
14 <bean class="org.springframework.http.MediaType">
15 <constructor-arg index="0" value="*" />
16 <constructor-arg index="1" value="*" />
17 <constructor-arg index="2" value="UTF-8" />
18 </bean>
19 </list>
20 </property>
21 </bean>
22 <!-- 避免IE執行AJAX時,返回JSON出現下載文件 -->
23 <bean id="fastJsonHttpMessageConverter"
24 class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
25 <property name="supportedMediaTypes">
26 <list>
27 <value>application/json;charset=UTF-8</value>
28 </list>
29 </property>
30 </bean>
31 </mvc:message-converters>
32 </mvc:annotation-driven>