问题描述
当URL中存在中文参数时,后台收到的参数值为乱码。
http://localhost:8080/test?desc=呵呵
项目环境
JSP + Spring MVC 3.2.8 + Tomcat 7
JSP中的编码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
web.xml中添加Spring的编码过滤器,这里有提到该过滤器要放在首位。
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
解决方法
- 首先URL中的中文要通过JS的
encodeURI
函数编码
var desc = encodeURI('呵呵');
var url = 'http://localhost:8080/test?desc=' + desc;
但是即使用encodeURI
编码过了,即使web.xml中使用了CharacterEncodingFilter
,后台接收到的参数仍然是乱码!因为CharacterEncodingFilter
只对POST请求的参数有用,GET请求不会通过他来编码,GET请求需要应用服务器来编码。
- 应用服务器设置
Tomcat 7
在server.xml中设置URIEncoding="UTF-8"
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
<system-properties>
<property name="org.apache.catalina.connector.URI_ENCODING" value="UTF-8"/>
<property name="org.apache.catalina.connector.USE_BODY_ENCODING_FOR_QUERY_STRING" value="true"/>
</system-properties>
Spring boot
# Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly.
spring.http.encoding.charset=UTF-8
# Enable http encoding support.
spring.http.encoding.enabled=true
# Force the encoding to the configured charset on HTTP requests and responses.
spring.http.encoding.force=true
https://stackoverflow.com/questions/24054648/how-to-configure-characterencodingfilter-in-springboot