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

首先摘錄 $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>

發佈了128 篇原創文章 · 獲贊 4 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章