2009年11月21日 星期六

tomcat6 encoding problem by GET/POST


撰寫jsp時,使用tomcat6引擎,常見接收中文出現亂碼,不像使用resin引擎方便,
這時只要作如下兩tomcat組態檔修改,
就可以接收表單的GET方式送來的中文big5碼,轉換成jsp內建的unicode.
這樣很方便作中文碼參數置入網址之測試,例如,http://host/cgi?q=%ac%ec.

/etc/tomcat6/server.xml

<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="big5" />


/etc/tomcat6/web.xml

<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>parameterEncoding</param-name>
<param-value>big5</param-value>
</init-param>

</servlet>

另外,發覺瀏覽器使用GET方式封裝中文參數於網址時,
有時會用big5,有時會用utf-8,視網頁如下宣告編碼(charset)而定,
<%@page contentType="text/html; charset=big5" import="java.io.*" %>
但作了如上2組態檔設定後,就只有big5送來的碼可正常轉換成unicode碼.
註:原來tomcat預設只接收"iso-8859-1"正常ascii編碼之參數.

至於表單用POST方式送來的big5中文碼參數,要正確轉換成unicode,
則.jsp程式碼需加上如下設定編碼指令才行.
request.setCharacterEncoding("big5");
query = request.getParameter("q");

參考資料:
http://minchuanwang.blogspot.com/2009/03/tomcat-post-get.html

沒有留言: