package com.itheima.web.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; @WebServlet("/selectUserServlet") public class SelectUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 接收用户名 String username = request.getParameter("username"); //2. 调用service查询User对象 //模拟成true boolean flag = true; //3. 响应标记 response.getWriter().write(""+flag); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>欢迎注册</title> <link href="css/register.css" rel="stylesheet"> </head> <body> <div class="form-div"> <div class="reg-content"> <h1>欢迎注册</h1> <span>已有帐号?</span> <a href="login.html">登录</a> </div> <form id="reg-form" action="#" method="get"> <table> <tr> <td>用户名</td> <td class="inputs"> <input name="username" type="text" id="username"> <br> <span id="username_err" class="err_msg" style="display: none">用户名已存在</span> </td> </tr> <tr> <td>密码</td> <td class="inputs"> <input name="password" type="password" id="password"> <br> <span id="password_err" class="err_msg" style="display: none">密码格式有误</span> </td> </tr> <tr> <td>验证码</td> <td class="inputs"> <input name="checkCode" type="text" id="checkCode"> <img src="imgs/a.jpg"> <a href="#" id="changeImg">看不清?</a> </td> </tr> </table> <div class="buttons"> <input value="注 册" type="submit" id="reg_btn"> </div> <br class="clear"> </form> </div> <script> //1.给用户名输入框绑定 失去焦点事件onblur document.getElementById("username").onblur = function () { //2. 发送AJAX请求 //获取用户名的值 var username = this.value; //2.1. 创建核心对象 var xhttp; if (window.XMLHttpRequest){ xhttp = new XMLHttpRequest(); }else { //code for IE6 IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //2.2. 发送请求 xhttp.open("GET","http://localhost:8080/ajax-demo/selectUserServlet?username="+username); xhttp.send(); //2.3. 获取响应 xhttp.onreadystatechange = function () { if (xhttp.readyState == 4 && xhttp.status == 200){ // alert(xhttp.responseText); //判断 if (this.responseText == "true"){ //用户存在,显示提示信息 document.getElementById("username_err").style.display = '';//设置id为username_err的style的display属性为空字符串 }else { //用户不存在,清除提示信息 document.getElementById("username_err").style.display = 'none';//设置id为username_err的style的display属性为none } } } } </script> </body> </html>
标签:username,用户名,验证,xhttp,用户,案例,import,servlet,javax From: https://www.cnblogs.com/Karl-hut/p/17523035.html