jsp页面
<head>
<script type="text/javascript" src="js/register.js" ></script>
</head>
<table>
<td>用户名:</td> <td> <input type="text" name="r_name " id="r_name" onblur="checkusername()" > <span id="span01 "></span> </td>
</table>
js文件夹下的register.js
//创建对象 function ajaxfunction() { var xmlhttp; try{ // 适用于ie7+, firefox, chrome, opera, safari xmlhttp=new xmlhttprequest(); } catch(e){ try{ //internet explorer xmlhttp=new activexobject("msxml2.xmlhttp"); } catch(e){ try{ // 适用于ie6, ie5 xmlhttp=new activexobject("microsoft.xmlhttp"); } catch(e){ xmlhttp=false; } } } return xmlhttp; }
var flag=ture; function checkusername(){ //获取jsp页面输入的值 var name=document.getelementbyid("r_name ").value; if(name==""||name==null){ document.getelementbyid("span01 ").innerhtml="<font color='red'>用户名不能为空!</font>" flag=false; }else{ //1.创建对象 var request=ajaxfunction() ; //2.发送请求 request.open("post","/studyweb/checkusernameservlet" ,true);//true表示异步提交 //注册状态改变监听,获取服务器传送过来的数据 request.onreadystatechange=function(){ //readystate==4表示请求已经完成,且响应已就绪。status==200表示“ok” if(request.readystate==4 && request.status==200){var data=request.responsetext; //获取checkusernameservlet中response中存储的值 if(data == 1){ document.getelementbyid("span01").innerhtml="<font color='red'>用户名已存在!</font>" flag=false; }else{ document.getelementbyid("span01").innerhtml="<font color='green'>√</font>" flag=true; } } } //如果是post方式带数据,那么这里要添加头,说明提交的数据类型是一个经过url编码的form表单数据 request.setrequestheader("content-type","application/x-www-form-urlencoded;charset=utf-8"); //带数据过去,在send方法里填写表单数据 request.send("name="+name ); } return flag; }
后台studyweb项目下的checkusernameservlet
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {//获取ajax发送过来的name值 string r_name=request.getparameter("name" ); try { //检验是否存在该用户名 boolean isexist=userservice.checkusername (r_name); system.out.println("isexist"+isexist); //通知页面,到底有没有 if(isexist){ response.getwriter().println(1);//存在用户名 }else{ response.getwriter().println(2);//不存在该用户 } } catch (exception e) { e.printstacktrace(); } }
userdaoimpl中方法的实现
public boolean checkusername (string u_name) { boolean flag=false; string sql="select u_id,u_name,u_password,u_email,u_phone from user where u_name=?"; conn=super.getconnection(); try { pstmt=conn.preparestatement(sql); pstmt.setstring(1,u_name); rs=pstmt.executequery();
//如果存在我输入的用户名和数据库表中已有的用户名相同时 if(rs.next()){
flag=true; } } catch (sqlexception e) { e.printstacktrace(); }finally{ super.closeall(conn, pstmt, stmt, rs); } return flag; }