System.out.println("中文"); System.out.println("中文".getBytes()); System.out.println("中文".getBytes("GB2312")); System.out.println("中文".getBytes("ISO8859_1")); System.out.println(new String("中文".getBytes())); System.out.println(new String("中文".getBytes(), "GB2312")); System.out.println(new String("中文".getBytes(), "ISO8859_1")); System.out.println(new String("中文".getBytes("GB2312"))); System.out.println(new String("中文".getBytes("GB2312"), "GB2312")); System.out.println(new String("中文".getBytes("GB2312"), "ISO8859_1")); System.out.println(new String("中文".getBytes("ISO8859_1"))); System.out.println(new String("中文".getBytes("ISO8859_1"), "GB2312")); System.out.println(new String("中文".getBytes("ISO8859_1"), "ISO8859_1"));
eg:判斷當前字符串的編碼格式。
//判斷當前字符串的編碼格式 if(destination.equals(new String(destination.getBytes("iso8859-1"), "iso8859-1"))) { destination=new String(destination.getBytes("iso8859-1"),"utf-8"); }
剛學習java的人,對於java中方法request.getParameter(“”),返回值若是中文,有時會莫名其妙的值變成了亂碼比較厭煩。
即使在處理中加入了
response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
但效果並沒有達到預期。究其原因在於以下幾點:
ServletRequest接口中定義了一個getCharacterEncoding方法,該方法用於返回請求消息中的實體內容的字符集編碼名稱。如果請求消息中沒有指定實體內容的字符集編碼名稱,則getCharacterEncoding方法返回null。
ServletRequest接口中定義了一個 setCharacterEncoding方法,該方法用於覆蓋請求消息中的實體內容的字符集編碼名稱的設置。getParameter和getReader方法將讀取到的實體內容從字節數組形態轉換成字符串返回時,都要參照請求消息中的實體內容的字符集編碼名稱,所以,setCharacterEncoding方法應早於getParameter或getReader方法之前進行調用。
ServletRequest對象的getParameter等方法以哪種字符集編碼對參數進行URL編碼,需記下以下三種情況:
(1) 對於HTTP請求消息的請求行中的URL地址后的參數,getParameter等方法進行URL解碼時所采用的字符集編碼在Servlet規范中沒有明確規定,它由各個Servlet引擎廠商自行決定。對於這種情況,Tomcat中的ServletRequest對象的getParameter等方法默認采用ISO8859-1字符集編碼進行URL解碼,因此無法返回正確的中文參數信息。
(2) 對於POST方式下的”application/x-www-form-urlencoded”編碼格式的實體內容,getParameter等方法以ServletRequest對象的getCharacterEncoding方法返回的字符集編碼對其進行URL解碼。事實上,對於IE瀏覽器產生的HTTP請求消息中沒有通過任何方式指定對實體內容進行URL編碼所采用的字符集編碼,那么,Servlet引擎將無法知道請求消息中的實體內容的字符集編碼,getCharacterEncoding()方法的返回值為null。對於這種情況,ServletRequest對象的getParameter等方法將使用默認的ISO8859-1字符集編碼對實體內容中的參數進行URL解碼,因此也將無法返回正確的中文參數信息。
(3) ServletRequest接口中定義了一個 setCharacterEncoding方法來設置請求消息中的實體內容的字符集編碼名稱,getParameter方法將以該方法設置的字符集編碼對實體內容進行URL解碼,所以,只要使用ServletRequest.setCharacterEncoding方法設置實體內容的字符集編碼為其URL編碼前的字符集編碼,那么getParameter方法就可以從實體內容返回正確的中文參數信息。但是,應該注意一點:ServletRequest.setCharacterEncoding方法設置的是請求消息中的實體內容的字符集編碼名稱,它只影響getParameter方法對POST方式下的”application/x-www-form-urlencoded”編碼格式的實體內容進行URL解碼的結果,而不能影響getParameter方法對HTTP請求消息的請求行中的URL地址后的參數進行URL解碼的結果。
所以在servlet開發中對於中文參數值的處理,完整代碼如下:
response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String name=Tool.ObjToStr(request.getParameter("name"), "美國"); if(name.equals(new String(name.getBytes("iso8859-1"), "iso8859-1"))) { name=new String(request.getParameter("name").getBytes("iso8859-1"),"utf-8"); }