2010年9月6日

J2EE Servlet request.getParameter() UTF-8 encoding issue

在J2EE平台開發Web Application,編碼是一個要小心處理的問題。儘管我們選擇整個系統採用一致的UTF-8編碼,卻有以下一堆設定要注意:
  1. JSP pageEncoding
  2. contentType in http header and html
  3. response.setCharacterEncoding
  4. request.setCharacterEncoding
  5. useBodyEncodingForURI
  6. URIEncoding
再搭配Groovy或Quercus(php)使用,除了file.encoding問題,還有GET/POST資料處理的編碼問題。

為了做最後一到防線,讓以後碰到編碼問題不必東改西改,我設計一個fetch method來解決GET/POST編碼問題。

pseduo code

class ServletHelper {
  method fetch ( name, defaultValue ) {
    if request.getParameter( name ) not exists {
        return defaultValue
    }
    if request.characterEncoding is UTF-8 {
      return request.getParameter( name ) as UTF-8
    }
    else {
      return request.getParameter( name )
    }
  }
}

2 則留言:

  1. 唉呀呀~~~身為頭號粉絲的我,居然沒注意到你已經update了好多篇新文章呀!
    but~~~底圖怎不是你的英姿呀!?
    倒是最下方偷偷掛上思創的名稱了唷! Good !!!

    回覆刪除
  2. 原來是你都沒來光顧,難怪最近流量掉了一半: ) 我還沒有足夠時間去改版面哩,暫時先這樣用一陣子。

    回覆刪除

lyhcode by lyhcode
歡迎轉載,請務必註明出處!