效果如下,当输入数据库中存在的用户名时,会显示"该用户名已经存在"
不存在时,显示“该用户名可以使用”
这里就不连接数据库了,用集合代替数据库
user.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>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(":input[name='user']").change(function(){
var val=$(this).val();
val=$.trim(val);
if(val!=""){
var url="${pageContext.request.contextPath}/chickuser";
var args={"user":val,"time":new Date()};
$.post(url,args,function(date){
$("#message").html(date);
})
}
})
})
</script>
<body>
<form action="" method="post">
username:<input type="text" name="user">
<div id="message"> </div>
<input type="submit" value="Submit">
</form>
</body>
</html>
对应的Servlet ChickuserServlet.java
package demo1;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ChickuserServlet
*/
@WebServlet("/chickuser")
public class ChickuserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user=request.getParameter("user");
String result=null;
//用集合代替数据库
List<String> username=Arrays.asList("aaa","bbb","ccc");
if(username.contains(user)){
result="<font color='red'>该用户名已经存在</font>";
}else{
result="<font color='green'>该用户名可以使用</font>";
}
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
response.getWriter().print(result);
}
}
通过请求var url="${pageContext.request.contextPath}/chickuser";回到chickuser对应的ChickuserServlet.java,处理一定的事务,通过response.getWriter().print(result);把结果显示出来,最后返回到前端页面的data