【AJAX】实现异步校验用户注册输入的用户名是否存在(核心代码)

 regist.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>Insert title here</title>
</head>
<body>
	<input type="text" name="userName" onchange="checkUserName(this);"><br>
	<input type="password" name="passwd">



</body>
<script type="text/javascript">
	var xmlHttpRequest = null;
	try{
		xmlHttpRequest = new XMLHttpRequest();
	}catch(e){
		try{
			xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
	}
	
	
	
	
	function checkUserName(userNameTag){
		var userName = userNameTag.value;
		//alert(userName  +"---------------" + xmlHttpRequest);
		var requestUrl = "${pageContext.request.contextPath}/checkUserName.action?userName=" + userName;
		xmlHttpRequest.open("get", requestUrl, true);
		xmlHttpRequest.send();
		xmlHttpRequest.onreadystatechange=function(){
			if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
				alert("服务端返回数据:" + xmlHttpRequest.responseText);
			}
			
		}	
		
	}


</script>
</html>

ChectUserServlet.java

package com.zzxtit.jsp35;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.zzxtit.jsp35.util.DBUtil;

@WebServlet("/checkUserName.action")
public class CheckUserServlet extends HttpServlet{

	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String userName = request.getParameter("userName");
		QueryRunner qr = new QueryRunner(DBUtil.getDS());
		String sql = "select * from user_infor where user_name = ? ";
		try {
			if(qr.query(sql,new BeanHandler<UserInfor>(UserInfor.class),userName) != null) {
				response.setContentType("text/html; charset=UTF-8");
				response.getWriter().write("用户名已存在!!!");
				System.out.println("用户名已存在!!!");
			}else {
				response.setContentType("text/html; charset=UTF-8");
				response.getWriter().write("注册成功!!!");
				System.out.println("注册成功!!!");
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("userName:" + userName);
		
		
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值