Encapsulate the XMLHttpRequest object to realize the ajax asynchronous login function; use three different methods to realize the login function,
Method 1: return the text content;
Method 2: return data in JSON format;
Method 3: Use fastJSON to generate JSON data and return to the front-end page;
Project structure
ajax.js file code
var xmlhttp=null; //Create XMLHttpRequest object function createHttpRequest(){ if(window.XMLHttpRequest){ //Mozilla browser xmlhttp = new XMLHttpRequest(); }else if(window. ActiveXObject){ try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); //New version of IE }catch(e){ try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){ xmlhttp = null; } } } if(!xmlhttp){ //failed to create XMLHttpRequest alert("Cannot create XMLHttpRequest object instance"); } } //send function function sendRequest(method,url,param,callbackHandler){ //Create object createHttpRequest(); //Binding event, the data returned by the background, processed by the callback method xmlhttp.onreadystatechange = callbackHandler; if(method=="get" || method=="GET"){ //Initialize sending information xmlhttp.open(method,url + "?" + param,true); xmlhttp. send(null); } if(method=="post" || method=="POST"){ //Initialize sending information xmlhttp.open(method,url,true); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlhttp. send(param); } }
Method 1 example
login.html source code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>System Login</title> <script src="../js/ajax.js"></script> <script type="text/javascript"> function dataDeal(){ if(xmlhttp.readyState == 4){ if(xmlhttp. status == 200) { document.getElementById("errMsg").innerText = xmlhttp.responseText; } else { alert(xmlhttp. status); } } } function login(){ var loginName = document.getElementById("loginName").value; var pass = document.getElementById("pass").value; if(loginName==""){ document.getElementById("loginNameTip").innerText="Please enter the user name"; document.getElementById("passTip").innerText=""; return; } if(pass==""){ document.getElementById("loginNameTip").innerText=""; document.getElementById("passTip").innerText="Please enter the login password"; return; } var url = "http://localhost:8080/ajaxProj/loginServlet"; var params = "loginName=" + loginName + " & amp;pass=" + pass; sendRequest("post",url,params,dataDeal); } </script> </head> <body> <h2 align="center">System login</h2> <table border="1" align="center" width="800"> <caption><font id="errMsg" color="red" size="2"></font></caption> <tr> <td align="right">Username:</td> <td><input type="text" name="loginName" id="loginName"> </td> <td width="200"><font color="red" size="2" id="loginNameTip"> & amp;nbsp;</font></td> </tr> <tr> <td align="right">Login password:</td> <td><input type="password" name="pass" id="pass"> </td> <td width="200"><font color="red" size="2" id="passTip"> & amp;nbsp;</font></td> </tr> <tr> <td align="center" colspan="3"> <input type="button" value="login" onclick="login();"> </td> </tr> </table> </body> </html>
LoginServlet.java
package com.servlet; import com.alibaba.fastjson.JSONObject; import com.bean.LoginBean; 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(name = "LoginServlet",value = "/loginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String loginName = request. getParameter("loginName"); String pass = request. getParameter("pass"); response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out = response. getWriter(); if(loginName.equals("admin") & amp; & amp; pass.equals("1234")){ //login successful out.write("Successful login"); }else{ //Login failed out.println("Login failed"); } out. close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
Operation effect
Method 2 case
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>System Login</title> <script src="../js/ajax.js"></script> <script type="text/javascript"> function dataDeal(){ if(xmlhttp.readyState == 4){ if(xmlhttp. status == 200) { document.getElementById("errMsg").innerText = xmlhttp.responseText; //The role of the JSON.parse method: convert the text content in json format into a JSON object var obj = JSON. parse(xmlhttp. responseText); if(obj. code==0){ alert(obj.msg); // Jump to other pages //location.href = "/ajaxProj/T2/menu.html" }else{ alert(obj.msg); } } else { alert(xmlhttp. status); } } } function login(){ var loginName = document.getElementById("loginName").value; var pass = document.getElementById("pass").value; if(loginName==""){ document.getElementById("loginNameTip").innerText="Please enter the user name"; document.getElementById("passTip").innerText=""; return; } if(pass==""){ document.getElementById("loginNameTip").innerText=""; document.getElementById("passTip").innerText="Please enter the login password"; return; } var url = "http://localhost:8080/ajaxProj/loginServlet"; var params = "loginName=" + loginName + " & amp;pass=" + pass; sendRequest("post",url,params,dataDeal); } </script> </head> <body> <h2 align="center">System login</h2> <table border="1" align="center" width="800"> <caption><font id="errMsg" color="red" size="2"></font></caption> <tr> <td align="right">Username:</td> <td><input type="text" name="loginName" id="loginName"> </td> <td width="200"><font color="red" size="2" id="loginNameTip"> & amp;nbsp;</font></td> </tr> <tr> <td align="right">Login password:</td> <td><input type="password" name="pass" id="pass"> </td> <td width="200"><font color="red" size="2" id="passTip"> & amp;nbsp;</font></td> </tr> <tr> <td align="center" colspan="3"> <input type="button" value="login" onclick="login();"> </td> </tr> </table> </body> </html>
LoginServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String loginName = request. getParameter("loginName"); String pass = request. getParameter("pass"); response.setContentType("text/json"); response.setCharacterEncoding("utf-8"); PrintWriter out = response. getWriter(); if(loginName.equals("admin") & amp; & amp; pass.equals("1234")){ //login successful //out.write("Successful login"); //data in json format is a key-value pair String msg = "{"code":"0","msg":"Login successful"}"; out.write(msg); }else{ //Login failed String msg = "{"code":"1","msg":"login failed"}"; out. println(msg); } out. close(); }
Operation effect
Method three case
Using fastjson: * 1. To download the jar package of fastjson, add it to the lib folder * 2. Click on the project structure and add the jar package to the dependency
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>System Login</title> <script src="../js/ajax.js"></script> <script type="text/javascript"> function dataDeal(){ if(xmlhttp.readyState == 4){ if(xmlhttp. status == 200) { document.getElementById("errMsg").innerText = xmlhttp.responseText; //The role of the JSON.parse method: convert the text content in json format into a JSON object var obj = JSON. parse(xmlhttp. responseText); if(obj.loginBean.code==0){ alert(obj.loginBean.msg); // Jump to other pages //location.href = "/ajaxProj/T2/menu.html" }else{ alert(obj.loginBean.msg); } } else { alert(xmlhttp. status); } } } function login(){ var loginName = document.getElementById("loginName").value; var pass = document.getElementById("pass").value; if(loginName==""){ document.getElementById("loginNameTip").innerText="Please enter the user name"; document.getElementById("passTip").innerText=""; return; } if(pass==""){ document.getElementById("loginNameTip").innerText=""; document.getElementById("passTip").innerText="Please enter the login password"; return; } var url = "http://localhost:8080/ajaxProj/loginServlet"; var params = "loginName=" + loginName + " & amp;pass=" + pass; sendRequest("post",url,params,dataDeal); } </script> </head> <body> <h2 align="center">System login</h2> <table border="1" align="center" width="800"> <caption><font id="errMsg" color="red" size="2"></font></caption> <tr> <td align="right">Username:</td> <td><input type="text" name="loginName" id="loginName"> </td> <td width="200"><font color="red" size="2" id="loginNameTip"> & amp;nbsp;</font></td> </tr> <tr> <td align="right">Login password:</td> <td><input type="password" name="pass" id="pass"> </td> <td width="200"><font color="red" size="2" id="passTip"> & amp;nbsp;</font></td> </tr> <tr> <td align="center" colspan="3"> <input type="button" value="login" onclick="login();"> </td> </tr> </table> </body> </html>
LoginServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String loginName = request. getParameter("loginName"); String pass = request. getParameter("pass"); //response.setContentType("application/json"); response.setContentType("text/json"); //response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out = response. getWriter(); LoginBean loginBean = new LoginBean(); loginBean. setCode(0); loginBean.setMsg("Login successful"); //Use fastjson to convert JSON format data JSONObject json = new JSONObject(); if(loginName.equals("admin") & amp; & amp; pass.equals("1234")){ //login successful json.put("loginBean",loginBean); String msg = json.toJSONString(); out.write(msg); }else{ //Login failed loginBean. setCode(1); loginBean.setMsg("username or password error"); json.put("loginBean",loginBean); //Convert the object to a string in JSON format String msg = json.toJSONString(); out. println(msg); } out. close(); }
running result
I have been engaged in software project development for more than 20 years. Since 2005, I have been engaged in teaching Java engineer series courses. I have recorded more than 50 high-quality video courses, including java basics, jspweb development, SSH, SSM, SpringBoot, SpringCloud, artificial intelligence, online payment, etc. Commercial projects, each course includes project practice, class PPT, and complete source code download, interested friends can take a look at my online classroom
Lecturer classroom link: https://edu.csdn.net/lecturer/893