Category Archives: Java

java form submit 中文亂碼問題

這個問題陸續遇到幾次了,始終知其然而不知其所以然。這是最近一次的處理案例:

環境

OS: CentOS 5.2 (utf-8)

Database: MySQL 5 (utf-8)

Application server: Tomcat 6

網頁

<input type=text name=keyword>

程式

String keyword=request.getParameter(“keyword”);

網頁的 input 輸入中文 submit 後由以上程式碼接取,原本的中文都變成亂碼。解決的方法是改用以下的接取程式碼,將收到的字串重新編碼。

String keyword=new String(request.getParameter(“keyword”).getBytes(“iso8859-1″),”utf-8”);

Why

Tomcat 在處理 GET、POST 參數時預設是採用 ISO-8859-1 編碼,請參考此 網址 URIEncoding 部份的說明,所以第2 段程式才會 work,請隨著您的作業系統及資料庫編碼設定,調整接取參數的程式碼。

Browser

以上的例子是送一個 keyword 到 tomcat web application 查詢資料,後來出現另一個問題,從 Firefox 送出中文的 keyword 可以正確的查到資料,Explorer 卻查不到,經過測試和查詢相關資料後發現,從 Explorer 送出 keyword 前要用 javascript encodeURIComponent() 編碼後再送出才會正常查到資料。

2008.11.27 加註

上面情形是發生在未指定 form 的 method,根據規格預設會以 get 傳送資料,Tomcat 的文件也沒有說明 URIEncoding 是會針對 get 或 post method 作處理。今天又遇到 form submit 中文亂碼問題,這次也不用重新編碼參數了,直接把 form method 設定 post,問題就解決了。看來 submit 的 form 有中文時,用 post method 會是比較好的選擇。

各種 Application Server URI encoding 的設定在這個 網址 有完整說明。

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Struts2 org.apache.struts2.ServletActionContext API 的 method 無法使用

想要寫個上傳檔案的程式,照慣例用 ServletActionContext 的 getServletContext().getRealPath() 來取得實際路徑,但是這個列在 API 的 method 卻沒有出現在 eclipse 的 清單中,網路上也找不到解決方法,最後發現是少了 servlet API 的 package。這個 package 如果是用 tomcat 的話,已經 bundle 了,不同 tomcat 版本在不同位置:

<tomcat 5.x>/common/lib/servlet-api.jar

<tomcat 6.x>/lib/servlet-api.jar

把 servlet-api.jar 複製到 web application 的 WEB-INF/lib 目錄下,再重新 build  project  即可。

註1:這個 jar 檔只有開發時需要,deploy 時因為 tomcat 已經 bundle 了,可以不要

註2:如果是用 myeclipse,IDE 在建新 web application project 時會自動處理好,不會有這個問題,付了費幫忙省下一些時間是一定要的啦

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

ERROR [org.apache.struts2.portlet.dispatcher.Jsr168Dispatcher] Could not find action

依據訊息來看,最大的可能是 struts.xml 沒有定義到 action,但是我 struts.xml 一個字一個字的檢查的十幾次,怕 class 打錯還特別從 source 檔 copy / paste 上去還是錯,最後找到的原因是 form tag 和 action setter 資料型態的的問題。

錯誤示範一、

<s:textarea name=”person.description”/>

person 是 hibernate tool 產生的物件,description 是 SQL 2000 ntext 欄位,java 資料型態是 java.sql.Clob,沒有轉換型態直接塞入物件就會 Could not find action 。

錯誤示範二、

<s:head theme=”ajax”/>

<s:datetimepicker name=”person.birthday”/>

birthday 是 SQL 2000 datetime 欄位,java 資料型態是 java.util.Date,同樣的直接塞進物件的結果和上個例子一樣,struts datetimepicker tag 文件有提到要先用 SimpleDateFormat 處理 submit 的資料。

2008.11.11 補充

不論是 portlet 或 struts web application 開發都有機會遇到 Could not find action 或 There is no Action mapped for action 的問題,目前整理 troubleshooting 的 checklist 如下:

  • struts 的 include 檔案是否都有正確 include 到,是否檔名打錯了
  • action 是否有 compile error 或資料型態轉換問題
  • 當 struts 的 package 有定義 namespace 時請使用絕對路徑,少用相對路徑,會減少很多的困擾

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...