代码:
Usermodel.java
package com.bean; public class Usermodel { public boolean validate(String username){ boolean valid=false; if("ajax".equals(username)){ valid=true; } return valid; } }
CheckUserServlet.java
package com.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.bean.Usermodel; public class CheckUserServlet extends HttpServlet { private static final long serialVersionUID = 1L; public CheckUserServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/xml"); PrintWriter out=response.getWriter(); Usermodel um=new Usermodel(); String user=request.getParameter("username"); out.println(um.validate(user)); out.flush(); out.close(); } protected void doPost(HttpServletRequest request,IOException { // TODO Auto-generated method stub doGet(request,response); } }
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>验证用户名是否可用</title> <script type="text/javascript"> var xmlhttp; function checkUserName() { var f=document.form1; var username=f.username.value; if(username==""){ alert("用户名不能为空"); f.username.focus(); return false; } else{ doCheckIt("CheckUserServlet","username="+username,"post"); } } function doCheckIt(url,params,method){ if(window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); } else if(window.ActiveXObject){ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } if(!xmlhttp){ alert("不能创建XMLHTTPRequest对象实例"); return false; } //请求对象处理程序 xmlhttp.onreadystatechange=processResponse; xmlhttp.open(method,url,true); //如果以POST方式请求,必须添加 xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlhttp.send(params); } String.prototype.trim=function(){ return this.replace(/^\s\s*/,'').replace(/\s\s*$/,''); }; function processResponse() { if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ if(xmlhttp.responseText.trim()=="false"){ document.getElementById("msg").innerHTML="恭喜!该用户名可用!"; } else{ document.getElementById("msg").innerHTML="对不起,该用户名已被使用"; } }else{ alert("网络出错!"); } } } </script> </head> <body> <form action="" name="form1" method="post"> 用户名<input type="text" id="uname" name="username" value="" onblur="checkUserName()" autocomplete="off"/> <div id="msg" style="display: inline;"></div> </form> </body> </html>
截图:
原文链接:https://www.f2er.com/ajax/161578.html