IE瀏覽器url帶中文引數導致亂碼問題(chrome下正常)
阿新 • • 發佈:2018-12-31
問題:
E瀏覽器下url帶中文請求引數,伺服器端使用new String(param.getBytes(“iso-8859-1”), “utf-8”)後仍然會亂碼。
但使用chrome瀏覽器則正常。
程式碼如下:
解決:
使用URLEncoder和URLDecoder對url引數進行編解碼。即,在jsp中對“小紅”進行URLEncode編碼後再傳參即可解決。
==================================================================================================================
但會導致另一個很奇怪的問題,想不明白。解決程式碼如下:
XMLHttpRequestTest.jsp function getAjax() { var xmlrequest = getXMLHttp(); xmlrequest.onreadystatechange = function() { //xmlrequest狀態變化,觸發函式 if(xmlrequest.readyState == 4) { // 4 資料接收完畢 if (xmlrequest.status == 200) { alert(xmlrequest.responseText); } } } var username = encodeURI("小紅"); //使用urlencoder進行中文的十六進位制轉碼。此時username值為"%E5%B0%8F%E7%BA%A2" xmlrequest.open("GET","${pageContext.request.contextPath}/xmlRequest?username="+username+"&password=123"); //xmlrequest.open("GET", "${pageContext.request.contextPath}/xmlRequest?username=小紅&password=123"); xmlrequest.send(null); }
疑問如下:
XMLHttpRequestTestServlet.java protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //問題一:jsp中使用了var username = encodeURI("小紅"); // 在jsp頁面中打斷點檢視發現username確實被轉碼成了"%E5%B0%8F%E7%BA%A2" // 但是在此處打斷點檢視username卻不是"%E5%B0%8F%E7%BA%A2",而是"å°çº¢",為什麼? String username = request.getParameter("username"); String password = request.getParameter("password"); //解決get方式請求引數亂碼 username = new String(username.getBytes("iso-8859-1"), "utf-8"); password = new String(password.getBytes("iso-8859-1"), "utf-8"); //問題二:如果URLEncoder是進行十六進位制的轉碼, // 那麼jsp頁面中使用了encodeURI(),伺服器端為什麼不需要使用URLDecoder也能輸出編碼前的中文? // username = URLDecoder.decode(username, "utf-8"); //解決響應亂碼 response.setContentType("text/html;charset=UTF-8"); System.out.println(username+" : "+password); response.getWriter().print("get 成功"); }
上述問題原因:url是不支援非ASCII字元的,當地址欄url路徑帶中文引數時,就會產生亂碼。
一般瀏覽器會自動幫我們進行urlencode的十六進位制編碼,並且urldecode的解碼也會由tomcat幫我們自動完成。
但IE瀏覽器不會幫我們自動進行urlencode編碼。
並且由於tomcat是外國人寫的,所以parameter的值是被iso-8859-1編碼,需要我們再進行一次utf-8的解碼。
即new String(param.getBytes(“iso-8859-1”), “utf-8”);