1. regist.jsp文件
<%@ page language="java" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>校验用户名是否存在</title>
<script type="text/javascript" src="./regist.js"> </script>
</head>
<body>
<center>
<form action="" enctype="application/x-www-form-urlencoded" method="post">
<h3>请填写用户注册信息</h3>
<table border="1">
<tr>
<td>用户名:</td>
<td><input type="text" name="username" value="" id="username">
<div id="divcheck"></div>
<input type="button" name="checkusername" value="查看用户名" id="checkusername"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="psw" value=""></td>
</tr>
<tr>
<td>确认密码:</td>
<td><input type="password" name="confpsw" value=""></td>
</tr>
<tr>
<td>出生日期:</td>
<td><input type="text" name="birthday" value=""></td>
</tr>
</table>
</form>
</center>
</body>
</html>
运行界面:
2.regist文件
window.onload=function(){
document.getElementById("checkusername").onclick=function(){
var username=document.getElementById("username").value;//获取text文本框中输入的值
//1.获取xhr对象
var xhr=ajaxFunction();
//2.监听
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
var data=xhr.responseText;
document.getElementById("divcheck").innerHTML=data;
}
}
}
//3.建立连接
xhr.open("post","../servlet/ValidateUsernameServlet");
//4.发送数据
//如果请求类型是POST方式的话,需要设置请求首部信息
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("username="+username);//把文本框中输入的用户名当做参数发送给服务器
}
}
function ajaxFunction(){
var xmlHttp;
try{ // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e){
try{// Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return xmlHttp;
}
3.ValidateUsernameServlet
package app.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidateUsernameServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
//模拟数据库
if(username==null||"".equals(username)){
response.getWriter().write("用户名不能为空!");
}else if("sa".equals(username)){
response.getWriter().write("用户名已经存在");
}else{
response.getWriter().write("用户名可以使用");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-09 01:38:16