|
一.概述
Tomcat对http请求的字符编码支持得有些混乱,使用起来动不动就发生乱码的情况。通过窥探tomcat的源码,对http request的字符编码这块的处理机制作一个总结。
tomcat内部对于http request,有两种字符编码的配置:
1. 对应get方式的http请求的字符编码
2. 对应post方式的http请求的字符编码
二.get方式的字符编码
第一种情况:get和post的编码保持一致,post方式的编码是什么,get方式的编码就是什么。
server.xml中进行如下配置的话,get方式的字符编码和post方式的字符编码保持一致。
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" useBodyEncodingForURI="true"/>
第二种情况:不指定useBodyEncodingForURI或者useBodyEncodingForURI="false"。
这时get和post的字符编码各自设置,互相没有关系。配置方法如下:
通过server.xml文件的URIEncoding进行设置,如果没有配置URIEncoding,那么用缺省的ISO-8859-1。
<Connector port="8080" maxThreads="150" minSpareThreads="25"
maxSpareThreads="75" enableLookups="false" redirectPort="8443"
acceptCount="100" debug="99" connectionTimeout="20000"
disableUploadTimeout="true" URIEncoding="UTF-8"/>
三.post方式的字符编码
1. 如果在servlet的doPost方法中或者filter中设置了request的字符编码,那么就以设置的为准。
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
//必须在getParameter,getParameterNames,getParameterValues方法调用之前进行设置
request.setContentType("UTF-8");
}
web.xml中配置filter
<filter>
<filter-name>SetCharacterEncoding</filter-name>
<filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
2. 如果没有进行1.的配置,那么从http header中取出content-type,然后从content-type的值中取出charset的值,
用charset的值作为post的字符编码。
如:content-type=application/x-www-form-urlencoded;charset=utf-8
那么,post的字符编码就是utf-8。
如果从http header中没有取到content-type或者charset,那么,就使用缺省的ISO-8859-1。 |
|
|
|
|
|
|