Ajax在注册用户时对用户名进行判断是否存在
1.创建一个VerifyUsernameServlet类
@WebServlet("/VerifyUsernameServlet")
public class VerifyUsernameServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
UserService userService=new UserService();
boolean isExist=true;
try {
User user=userService.selectByname(username);
if(user==null) {
isExist=false;
}
response.getWriter().append("{\"isSuccess\":"+!isExist+"}");
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.对注册页面进行修改
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("input[name='username']").blur(verifyUsername);
});
function verifyUsername(){
$.ajax({
url:encodeURI("${pageContext.request.contextPath }/VerifyUsernameServlet"),
type:"post",
data:{
username:$("input[name='username']").val()
},
dataType:"json",
success:function(msg){
if(msg.isSuccess){
$("#msg").html("<font color='green'>用户名可以用!</font>");
}else{
$("#msg").html("<font color='red'>用户名重复!</font>");
}
}
});
}
</script>
</head>
<body>
<%
Object o=request.getAttribute("erro");
if(o!=null)
out.print(o+"<br/>");
%>
<form action="<%=request.getContextPath() %>/register_do" method="post">
用户名:<input type="text" name="username" /><div id="msg"></div><br/>
密码:<input type="password" name="password" /><br/>
年龄:<input type="text" name="age" /><br/>
性别: 男<input type="radio" name="sex" value="T" checked="checked"/>
女<input type="radio" name="sex" value="F" /><br/>
<input type="submit" value="注册" />
</form>
</body>
</html>