1.创建lib文件导入javaee-api-7.0.jar
2.在src目录下创建一个servlet类,实现对前端消息的响应处理
package servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(urlPatterns = "/testuname")
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.接收参数
String username = req.getParameter("username");
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
if("admin".equals(username)){
writer.println("账户已被注册");
}else {
writer.println("账户可用!");
}
}
}
3.在index.jsp中编写js消息发送函数
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/6/24
Time: 20:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<script type="text/javascript">
function test() {
//发送异步请求
//1.创建XMLHttpRequest对象
var xmlhttp;
if(window.XMLHttpRequest){
//IE浏览器
xmlhttp=new XMLHttpRequest();
}else if(window.ActiveXObject){
xmlhttp=new ActiveXObject("Microssft.XMLHTTP");
}
//2.打开链接
var uname=document.getElementById("uname").value;
xmlhttp.open("get","/testuname?username="+uname,true);
//3.指定回调函数
xmlhttp.onreadystatechange=function () {
//3.1判断状态,==4---成功返回了
if(xmlhttp.readyState==4 || xmlhttp.status==200){
//3.2接收返回的数据
var responseText = xmlhttp.responseText;
document.getElementById("rs").innerText=responseText;
}
}
//4.发送数据
xmlhttp.send();
}
</script>
<body>
<h1>ajax用户名注册验证</h1>
username:<input type="text" onblur="test()" id="uname"><span id="rs"></span>
</body>
</html>
4.创建的项目不要忘记引入tomcat服务器,最后启动服务器,在浏览器中查看。