您的位置:首页 > 运维架构 > Tomcat

Tomcat 7源码学习笔记

2013-01-28 23:48 417 查看
接触tomcat7一段时间了,但对这个http请求的字符编码耿耿于怀,网上很多的文章只写皮毛,而且也忽视Tomcat版本,我发现这篇文章从源码角度分析的比较彻底,拿来收藏,望对各位有用.

转载自:http://www.17jquery.com/java/48506/

原文:

一.概述

Tomcat对http请求的字符编码支持得有些混乱,使用起来动不动就发生乱码的情况。通过窥探tomcat的源码,对http request的字符编码这块的处理机制作一个总结。

内容来自17jquery
tomcat内部对于http request,有两种字符编码的配置:

1. 对应get方式的http请求的字符编码

2. 对应post方式的http请求的字符编码 内容来自17jquery

二.get方式的字符编码 内容来自17jquery

第一种情况:get和post的编码保持一致,post方式的编码是什么,get方式的编码就是什么。

server.xml中进行如下配置的话,get方式的字符编码和post方式的字符编码保持一致。
内容来自17jquery
<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。一起jquery,17jquery

17jquery.com

<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方式的字符编码

一起jquery,17jquery

1. 如果在servlet的doPost方法中或者filter中设置了request的字符编码,那么就以设置的为准。

public void doPost(HttpServletRequest request,HttpServletResponse response)

throws IOException,ServletException{

//必须在getParameter,getParameterNames,getParameterValues方法调用之前进行设置17jquery.com

request.setContentType("UTF-8"); 内容来自17jquery

} jquery.com

web.xml中配置filter 17jquery.com

<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> 一起jquery,17jquery

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: