本篇內容:
(1)上一篇是使用同步的請求實現登陸,並由 Servlet 決定登錄後下一步作哪些事情,本篇使用 jQuery Ajax 的方式,實現異步登陸,登陸成功後執行的內容在 js 中定義。
(2)在登陸以前,在 js 中驗證表單中的,用戶名是否爲空,密碼是否爲空,密碼是不是 6-12 位,登陸失敗後,返回提示信息。
(3)登陸成功後,返回用戶表的全部信息,以表格形式展現:
(4)效果截圖:javascript
本篇部份內容看起來和上一篇類似,但又不少改動,請認真查看。css
(建議名稱一致,建庫同上一篇,再介紹一次)html
(1)安裝 MySQL 請百度或參考:MySQL 安裝 + 入門大全 + 經常使用命令合集前端
(2)打開 cmd ,登陸 mysql 的 root 用戶,建立 studb 數據庫,建立表 tb_user :java
(3)顯示錶結構,插入 3 條用戶數據:node
(4)數據庫 studb,表 tb_user 建立好了。mysql
(1)建立項目和修改目錄結構,由於經常使用,因此寫在了單獨的一篇文章,請查看:Spring 筆記 -05- 建立 Maven Web 項目 + Tomcat 及目錄結構配置。jquery
(2)序號(1)中說的,一篇文章,所有須要!ajax
(3)配置 Maven 的配置文件 pom.xml 文件,位置在下面有提示:sql
本篇多加一個 fastjson,請注意!!
請更新爲下面的 pom 最新配置:
<dependencies> <!-- 本篇多加一個 fastjson,請注意 --> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.54</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> </dependencies>
(4)點擊自動導入:
(5)建立以下目錄及文件:
(6)下面須要先作一件事,就是在 js 目錄中,引入 Bootstrap3 和 jQuery
注意:只能是 Bootstrap3 版本:
配置步驟:
npm install bootstrap3
npm install jQuery
貼代碼前,先看一下整個完整的項目目錄結構:
前臺文件:
後臺文件目錄結構:
全部文件代碼:
(1)findUserInfoForAjax.html 文件,用於登陸成功時跳轉,該文件在瀏覽器打開時,js 會執行一個 findAllUser 方法,先請求 Servlet,而後 Servlet 去查詢數據庫信息,創 User 實體類,再轉換成 json 數據格式,前端處理 json 數據,再顯示在頁面中:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>findUserInfoForAjax</title> <link rel="stylesheet" href="js/node_modules/bootstrap3/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="js/node_modules/bootstrap3/dist/css/bootstrap-theme.css"> <script type="text/javascript" src="js/node_modules/jquery/dist/jquery.min.js"></script> <script> function findAllUser() { $.ajax({ url:"userServletForAjax", method:"get", //dataType:"jsonp", //async:true, success:function (result) { var obj = JSON.parse(result); var str = ""; $.each(obj,function (index,row,ee) { str+="<tr><td>"+row.id+"</td><td>"+row.uname+"</td><td>" +row.upwd+"</td><td>"+row.lastLoginTime+"</td><td>"+row.role+"</td></tr>" }); $("#alluser").html(str); }, error:function () { alert("服務器請求失敗") } }) } findAllUser(); </script> </head> <body> <table class="table table-striped table-hover"> <tr> <td>id</td> <td>uname</td> <td>upwd</td> <td>lastLoginTime</td> <td>role</td> </tr> <tbody id="alluser"> </tbody> </table> </body> </html>
(2)login_ajax.html 文件,是登陸的前端界面,在請求 Servlet 以前,會先檢查數據的格式,有用戶名是否爲空,密碼是否爲空,密碼是否爲 6-12 位。
當格式正確再去請求,驗證數據庫中的用戶信息是否匹配,成功則跳轉到上面的 findUserInfoForAjax.html 文件,不成功提示用戶名或密碼錯誤!:
源代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用戶登陸</title> <link rel="stylesheet" href="js/node_modules/bootstrap3/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="js/node_modules/bootstrap3/dist/css/bootstrap-theme.css"> <script type="text/javascript" src="js/node_modules/jquery/dist/jquery.min.js"></script> <script type="text/javascript"> function login() { var uname = $("#uname").val(); var upwd = $("#upwd").val(); if (uname == null || uname == "") { $("#unameMsg").html("用戶名不能爲空!"); return; } else $("#unameMsg").html(""); if (upwd.length == 0) { $("#upwdMsg").html("密碼不能爲空!"); return; } else $("#upwdMsg").html(""); if (upwd.length < 6 || upwd.length > 12) { $("#upwdMsg").html("密碼應該在 6-12 位之間!"); return; } else $("#upwdMsg").html(""); $.ajax({ url: "Servlet", method: "get", data: { "uname": $("#uname").val(), "upwd": $("#upwd").val(), "role": $("#role").val() }, success: function (result) { if (result == "1") { window.location.href = "findUserInfoForAjax.html"; } else { $("#loginMsg").html("登陸失敗,請重試!"); } }, error: function () { alert("請求服務器失敗!"); } }); } </script> </head> <body> <br><br> <br><br> <form name="loginForm" id="loginForm"> <div class="center-block" style="width: 45%;height: 350px"> <div class="panel panel-primary"> <div class="panel-heading"> <span class="glyphicon glyphicon-apple"></span>用戶登陸 </div> <div class="panel-body"> <div class="text-success" align="center"> <h3>歡迎使用資源統一管理系統</h3> </div> <div class="input-group"> <label class="input-group-addon">用戶名</label> <input class="form-control" type="text" id="uname" name="uname" placeholder="請輸入用戶名"> <label class="input-group-addon text-warning">*</label> </div> <label id="unameMsg" style="color: red"></label><br> <div class="input-group"> <label class="input-group-addon">密 碼</label> <input class="form-control" type="password" id="upwd" name="upwd" placeholder="請輸入密碼"> <label class="input-group-addon text-warning">*</label> </div> <label id="upwdMsg" style="color: red"></label><br> <div class="input-group"> <label class="input-group-addon">權 限</label> <select name="role" class="form-control "> <option value="admin">管理員</option> <option value="teacher">經理</option> <option value="student">用戶</option> </select> </div> </div> <div align="center"> <label id="loginMsg" style="color: red"></label> <a href="javascript:login()" class="btn btn-danger"><span class="glyphicon glyphicon-log-in"></span> 登陸</a> <a href="javascript:loginForm.reset()" class="btn btn-primary"><span class="glyphicon glyphicon-remove"></span> 重置</a> </div> <br> <div class="panel-footer"> <div align="center"> ©2018-2019 肖朋偉的 CSDN 博客 Copy Right </div> </div> </div> </div> </form> </body> </html>
若是成功引入 Bootstrap3 ,打開服務器,打開本頁面,會有下面界面:
(3)User.java 文件(有更新):
package com.pojo; //用來存放用戶登陸時,輸入輸出的信息 public class User { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } private String uname; private String upwd; private String lastLoginTime; public String getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(String lastLoginTime) { this.lastLoginTime = lastLoginTime; } private String role; public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getUpwd() { return upwd; } public void setUpwd(String upwd) { this.upwd = upwd; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
(4)UserDAO.java 文件(有更新):
package com.dao; import com.dbutil.DBUtils; import com.pojo.User; import java.util.List; public class UserDAO { public List<User> findAllUser(){ DBUtils dbUtils = new DBUtils(); return dbUtils.findAllUser(); } //返回 0 或 1 public int login(User user){ DBUtils dbUtils = new DBUtils(); //與數據庫是否匹配,匹配爲 1 int temp = dbUtils.login(user); return temp; } }
(5)DBUtils.java 文件:
!!! 成敗在與這個文件
package com.dbutil; import com.pojo.User; import java.sql.*; import java.util.ArrayList; import java.util.List; public class DBUtils { Connection conn; //預處理 PreparedStatement pstmt; //結果集 ResultSet rs; public DBUtils(){ try{ Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC","root","xiaopengwei"); } catch (Exception e){ e.printStackTrace(); } } public int login(User user){ try{ pstmt=conn.prepareStatement("select * from tb_user where uname = ? and upwd = md5(?)"); pstmt.setString(1, user.getUname()); pstmt.setString(2, user.getUpwd()); rs = pstmt.executeQuery(); if (rs.next()) return 1; else return 0; }catch (Exception e){ e.printStackTrace(); } return 0; } //查詢數據庫中 tb_user 表的全部信息 public List<User> findAllUser() { try { String sql = "select * from tb_user"; //預處理 pstmt = conn.prepareStatement(sql); //執行查詢 rs = pstmt.executeQuery(); //實例化 List<User> list = new ArrayList<User>(); while (rs.next()) { User user = new User(); user.setId(rs.getInt(1)); user.setUname(rs.getString(2)); user.setUpwd(rs.getString(3)); user.setLastLoginTime(rs.getString(4)); user.setRole(rs.getString(5)); list.add(user); } return list; } catch (Exception e) { System.out.println(e.getMessage()); } return null; } }
(6)Servlet.java 文件:
package com.loginServlet; import com.pojo.User; import com.service.UserService; 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; import java.sql.PreparedStatement; @WebServlet(name = "Servlet",urlPatterns = "/Servlet") public class Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doPost"); request.setCharacterEncoding("utf-8"); //獲取 post 請求中的兩個參數 String uname = request.getParameter("uname"); String upwd = request.getParameter("upwd"); String role = request.getParameter("role"); /*硬編碼, 不從數據庫獲取信息,直接驗證 if (uname.equals("admin") && upwd.equals("123456")) { response.sendRedirect("index.jsp"); }else{ response.sendRedirect("loginServlet.html"); }*/ //從服務獲取值 UserService userService = new UserService(); User user = new User(); user.setUname(uname); user.setUpwd(upwd); user.setRole(role); if (userService.login(user)) { //向服務器要數據 //登陸成功跳轉 index.jsp response.sendRedirect("index.jsp"); }else{ response.sendRedirect("failed.jsp"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uname = request.getParameter("uname"); String upwd = request.getParameter("upwd"); String role = request.getParameter("role"); System.out.println("doGet"); System.out.println(uname+":"+upwd+"-"+role); UserService userService = new UserService(); User user = new User(); user.setUname(uname); user.setUpwd(upwd); user.setRole(role); boolean login = userService.login(user); PrintWriter out = response.getWriter(); if (login) out.print("1"); else out.print("0"); out.close(); } }
(7)UserServletForAjax.java 文件:
package com.dbutil; import com.pojo.User; import java.sql.*; import java.util.ArrayList; import java.util.List; public class DBUtils { Connection conn; //預處理 PreparedStatement pstmt; //結果集 ResultSet rs; public DBUtils(){ try{ Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC","root","xiaopengwei"); } catch (Exception e){ e.printStackTrace(); } } public int login(User user){ try{ pstmt=conn.prepareStatement("select * from tb_user where uname = ? and upwd = md5(?)"); pstmt.setString(1, user.getUname()); pstmt.setString(2, user.getUpwd()); rs = pstmt.executeQuery(); if (rs.next()) return 1; else return 0; }catch (Exception e){ e.printStackTrace(); } return 0; } //查詢數據庫中 tb_user 表的全部信息 public List<User> findAllUser() { try { String sql = "select * from tb_user"; //預處理 pstmt = conn.prepareStatement(sql); //執行查詢 rs = pstmt.executeQuery(); //實例化 List<User> list = new ArrayList<User>(); while (rs.next()) { User user = new User(); user.setId(rs.getInt(1)); user.setUname(rs.getString(2)); user.setUpwd(rs.getString(3)); user.setLastLoginTime(rs.getString(4)); user.setRole(rs.getString(5)); list.add(user); } return list; } catch (Exception e) { System.out.println(e.getMessage()); } return null; } }
(8)UserService.java 文件:
package com.service; //服務層,給控制層提供服務 import com.dao.UserDAO; import com.pojo.User; import java.util.List; public class UserService { UserDAO dao = new UserDAO(); //存用戶數據 public List<User> findAllUser(){ return dao.findAllUser(); } //參數,處理 User 對象,返回 True 或 False public boolean login(User user){ int temp = dao.login(user); if (temp == 0) return false; else return true; } // DBUtils dbUtils = new DBUtils(); }
(1)MySQL 8.0 版本的 jdbc 個數據版本不匹配
(2)數據庫服務沒有運行
(3)配置文件數據庫信息沒有自行更改
(4)文件名自定義時,依賴失敗