通常,在使用Spring MVC框架的应用程序中,为了解决中文参数乱码的问题,都会添加如下过滤器配置:
<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>
但是,在Tomcat下运行时,对于GET请求参数的处理和POST参数不同,会出现POST中文参数正常,但是GET请求中文参数乱码的情形。
通过查看Tomcat相关源码得知,为了处理GET请求中的中文参数乱码问题,必须明确设置Connector的URIEncoding属性为指定编码。
具体配置如下:
<Connector port="8000" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="utf-8"/>
org.apache.catalina.connector.CoyoteAdapter类service()方法源码片段如下:
@Override public void service(org.apache.coyote.Request req, org.apache.coyote.Response res) throws Exception { Request request = (Request) req.getNote(ADAPTER_NOTES); Response response = (Response) res.getNote(ADAPTER_NOTES); if (request == null) { // Create objects request = connector.createRequest(); request.setCoyoteRequest(req); response = connector.createResponse(); response.setCoyoteResponse(res); // Link objects request.setResponse(response); response.setRequest(request); // Set as notes req.setNote(ADAPTER_NOTES, request); res.setNote(ADAPTER_NOTES, response); // Set query string encoding req.getParameters().setQueryStringEncoding(connector.getURIEncoding()); // 显然,在处理GET查询参数编码时是获取Connector的URIEncoding属性 } ... }