2016年2月20日 星期六

JSP 中文處理(Tomcat)

若你使用Tomcat並採用POST,或你沒有設定setCharacterEncoding(),且已取得一個請求參數字串,另外一個處理編碼的方式,則是透過String的getBytes()指定編碼來取得該字串的位元組陣列,然後再重新建構為正確編碼的字串。
例如若瀏覽器使用UTF-8處理字元,Web容器預設使用ISO-8859-1編碼,則正確處理編碼的方式為:
<%
  String val = request.getParameter("data");
  String encode = new String(val.getBytes("ISO-8859-1"), "UTF-8");
  out.print("Data: " + encode);
%>

JAVA API  String
constructor
String(byte[] bytes, Charset charset)
Constructs a new String by decoding the specified array of bytes using the specified charset.

method

getBytes

public byte[] getBytes(String charsetName)
                throws UnsupportedEncodingException
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

沒有留言:

張貼留言