當採用post方式向伺服器發送請求時,並且表單中被輸入了中文時,往往會出現亂碼的狀況。
解決的方法: 在接收請求的Servlet中加上如下代碼:
request.setCharacterEncoding("UTF-8");
對於利用Ajax發送post請求,瀏覽器統一使用UTF-8進行編碼。此行代碼的作用就是以編程的方式指定讓Tomcat伺服器以UTF-8進行解碼,這樣編碼和解碼就保持了一致。
測試代碼如下:
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";xhr.open("post",url,true);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.send("username="+document.getElementById('n1').value);}</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");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");}}}