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);
}
}