當採用get方式向伺服器發送請求時,並且表單中被輸入了中文時,往往會出現亂碼的狀況。
解決的方法分兩步走:
① 在利用Ajax發送get請求時,將url放在encodeURI( )的括弧裡。
② 在Tomcat伺服器的安裝目錄下,找到conf檔案夾下的server.xml,在
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443"/>
的末尾加上URIEncoding="UTF-8",
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/>
解釋:第一步的作用就是以編程的方式強行指定表單的中文資料以UTF-8進行編碼,第二步的作用就是修改Tomcat伺服器的預設解碼方式為UTF-8。這樣編碼和解碼方式就保持了一致,亂碼也就不會出現了。需要注意的一點是,不要企圖用request.setCharacterEncoding("UTF-8")指定伺服器的解碼方式,原因是這行代碼僅僅對post請求起作用,對於get請求是沒有作用的。
測試代碼如下:
register.jsp :
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%><html><head><title>Insert title here</title><script type="text/javascript" src="js/prototype1.6.js"></script><script type="text/javascript">function getXmlHttpRequest(){var xhr=null;if((typeof XMLHttpRequest)!='undefined'){xhr=new XMLHttpRequest();}else{xhr=new ActiveXObject("Microsoft.XMLHttp");}return xhr;}function valiUsername(){var xhr=getXmlHttpRequest();xhr.onreadystatechange=function(){if(xhr.readyState==4){if(xhr.status==200){var doc=xhr.responseText;document.getElementById('username_msg').innerHTML=doc;}else{document.getElementById('username_msg').innerHTML="系統錯誤...";}}else{document.getElementById('username_msg').innerHTML="驗證中...";}}var url="valiusername.do?username="+document.getElementById('n1').value;xhr.open("get",encodeURI(url),true);xhr.send(null);}</script></head><body><form action="register.do" method="post">姓名:<input type="text" name="username" id="n1" onblur="valiUsername();"><span style="color:red" id="username_msg"></span><br>密碼:<input type="password" name="password"><br><input type="submit" value="註冊"></form></body></html>
UsernameServlet.java :
public class UsernameServlet extends HttpServlet {public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//request.setCharacterEncoding("UTF-8");//此行代碼僅對post請求有效String uri=request.getRequestURI();String path=uri.substring(uri.lastIndexOf("/"),uri.lastIndexOf("."));response.setContentType("text/html;charset=UTF-8");PrintWriter pw=response.getWriter();if(path.equals("/valiusername")){String username=request.getParameter("username");System.out.println("姓名:"+username);if(username.equals("格林")){pw.println("使用者名稱已經佔用");}else{pw.println("使用者名稱可以使用");}}if(path.equals("/register")){String username=request.getParameter("username");String password=request.getParameter("password");response.sendRedirect("login.jsp");}}}