现在的位置: 首页 > 综合 > 正文

tomcat5.0.19 post和get 中文解决方法

2013年09月16日 ⁄ 综合 ⁄ 共 2461字 ⁄ 字号 评论关闭
首先摘录 $TOMCAT_HOME/webapps/tomcat-docs/config/http.html中的两个参数解释: URIEncoding:This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, ISO-8859-1 will be used.
useBodyEncodingForURI:This specifies if the encoding specified in contentType should be used for URI query parameters, instead of using the URIEncoding. This setting is present for compatibility with Tomcat 4.1.x, where the encoding specified in the contentType, or explicitely set using Request.setCharacterEncoding method was also used for the parameters from the URL. The default value is false.
上述二個 Tomcat 參数,是設定在 server.xml 中的 http 区域,要解决 QueryString 中文乱码的问題,你必須至少设定二个参数其中之一。 URIEncoding 请设定为URIEncoding="ISO-8859-1" 指定为"ISO-8859-1" 编码,让 QueryString 的字元编码和 post body 相同。 useBodyEncodingForURI 这是用來相容 Tomcat 4.x 版的,设定的值是 "true" or "false",意思是指 "要不要让 QueryString 与 POST BODY 用相同的字节编码 ?",若是设成 true,那也可达到 "ISO-8859-1" 编码的需求。 建议,用 URIEncoding 的设定,毕竟 useBodyEncodingForURI 的作法是为了相容 Tomcat 4.X。不过若照原文的說明,理论上这二个參数都不设,Tomcat 也该用 "ISO-8859-1" 的编码,那为什么是会有问题呢 ? 是因为 Tomcat Source Code 中关于 QueryString 程序的bug,所以,還是必須在 Server.xml 中,加上 URLEncoding 的參數設定才行哦。 Connector 的設定範例:
<Connector
debug="0"
acceptCount="100"
connectionTimeout="20000"
disableUploadTimeout="true"
port="80"
redirectPort="8443"
enableLookups="false"
minSpareThreads="25"
maxSpareThreads="75"
maxThreads="150"
maxPostSize="0"
URIEncoding="ISO-8859-1"
>
</Connector>

 //注意,经过本人实验,设定URIEncoding="ISO-8859-1"后get方式依然是乱码,但是将其改为URIEncoding="gb2312"即可。
在這邊我做幾項補充 ... 一般說來,我們在使用 Tomcat 4 透過 GET or POST 的方式傳參數時,通常都是使用 Filter 的方式來解決中文傳參數的問題。 但是到了 Tomcat 5.0.19 之後,解決中文傳遞參數時,就必須考慮是使用 GET or POST,兩種解決的方式不一樣。 如果是使用 GET 的方式傳遞時,就如同 精靈 兄 的文章所述,或者使用 String name1 = new String((request.getParameter("name")).getBytes("ISO-8859-1"),"gb2312"); ;若是使用 POST 的方式時,就延用傳統一般解決中文的方式 request.setCharacterEncoding("Big5"); 不過當初我最後的做法是使用 Filter 的方式 Filter 的做法就是:先判斷是使用那種傳遞方式( GET or POST),假若是用 GET 的方式就採用第一種 code;若使用POST 方式,就採用第二種 code。

另外,解决post也可以使用filter来解决:
1 实现一个Filter.设置处理字符集为GBK。(在tomcat的webapps/servlet-examples目录有一个完整的例子。请参考web.xml和SetCharacterEncodingFilter的配置。)

首先在jsp页面上添加:<%@ page contentType="text/html;charset=gb2312"%>

1)只要把%TOMCAT安装目录%/ webapps/servlets-examples/WEB-INF/classes/filters/SetCharacterEncodingFilter.class文件拷到你的webapp目录/filters下,如果没有filters目录,就创建一个。
2)在你的web.xml里加入如下几行:


<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

抱歉!评论已关闭.