当采用post方式向服务器发送请求时,并且表单中被输入了中文时,往往会出现乱码的状况。
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"); } } }原文链接:https://www.f2er.com/ajax/166224.html