注册页面的异步交互
思路如下:创建注册页面,创建servlet响应数据,servlet查询到数据库所有的用户名,得到页面输入的用户名的值,判断是否跟数据库的用户名重复,如果重复,利用Ajax响应页面。
注册页面:仅为测试,无好看的样式
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<form action="/addServlet" method="post">
用户名<input id="user" type="text" name="username"/>
<span id="dulp" style="display:none;color: red">用户名已存在</span>
<br/>
密码 <input type="password" name="password"><br/>
<input type="submit">
</form>
<script>
document.getElementById("user").onblur=function () {
var xhttp=new XMLHttpRequest();
var username=this.value;
xhttp.open("GET","http://localhost:8088/selectAllServlet?username="+username,true)
xhttp.send("")
xhttp.onreadystatechange=function() {
if(this.readyState=4&&this.status==200){
if(this.responseText=="true"){
document.getElementById("dulp").style.display='';
}
else {
document.getElementById("dulp").style.display="none";
}
}
}
}
</script>
</body>
</html>
servlet响应
@WebServlet(urlPatterns = "/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
private UserService userService = new UserService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<UserInfo> userInfos = userService.selectAll();
String t = request.getParameter("username");
for (UserInfo userInfo : userInfos) {
if(userInfo.getUserName().equals(t)){
response.getWriter().write("true");
System.out.println(true);
return;
}
}
}
}