制作一个前端登录界面,制作一个简单的web服务器,连接数据库,验证从前端界面提交的表单数据。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>登录</title> <link href="loginDemo.css" rel="stylesheet" type="text/css" /> <script src="loginDemo.js" type="text/javascript"></script> </head> <body> <div class="box"> <form action="http://127.0.0.1:8080/WebBack/login" method="post" > <span class="account_label_class">账户:</span> <input type="text" name="account" id="account_id" class="account_class" onblur="accountIsEmpty()" /> <span id="account_tips_id" class="account_tips_class"></span> <div style="clear: left;"></div> <br /> <span class="password_label_class">密码:</span> <input type="password" name="psw" id="password_id" class="password_class" onblur="passwordIsEmpty()" /> <span id="password_tips_id" class="password_tips_class"></span> <div style="clear: left;"></div> <br /> <input type="submit" value="登录" class="submit_button_class" /> </form> </div> </body> </html>
*{ margin: 0; padding: 0; } body{ background-image: url(img/login_bg.jpg); background-size: 100%; } .box{ background-color: whitesmoke; width: 400px; height: 300px; border-radius: 30px; margin: auto; margin-top: 200px; text-align: center; } span,input{ float: left; } .account_label_class,.password_label_class{ margin-top: 40px; margin-left: 40px; } .account_class,.password_class,.account_tips_class,.password_tips_class{ margin-top: 40px; margin-left: 10px; } .submit_button_class{ width: 80px; height: 40px; background-color: skyblue; border-radius: 10px; margin-left: 160px; margin-top: 40px; }
function accountIsEmpty() { var accountObj = document.getElementById("account_id"); var tipsObj = document.getElementById("account_tips_id"); if (accountObj.value.length == 0 || accountObj.value.length > 15) { tipsObj.style.color = "red"; tipsObj.style.fontSize = "12px"; tipsObj.innerHTML = "× 为空或大于十五"; } else{ tipsObj.style.color = "green"; tipsObj.innerHTML = "√"; } } function passwordIsEmpty() { var passwordObj = document.getElementById("password_id"); var tipsObj = document.getElementById("password_tips_id"); if (passwordObj.value.length == 0 || passwordObj.value.length > 15) { tipsObj.style.color = "red"; tipsObj.style.fontSize = "12px"; tipsObj.innerHTML = "× 为空或大于十五"; } else{ tipsObj.style.color = "green"; tipsObj.innerHTML = "√"; } }
package com.ffyc.webback.Dao; import java.sql.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class LoginDao { static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/feifan_test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"; // 数据库的用户名与密码,需要根据自己的设置 static final String USER = "root"; static final String PASS = "root"; public static List getElementArray(String key){ List<String> array = new ArrayList<>(); Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 // Class.forName(JDBC_DRIVER); // DriverManager.registerDriver(new Driver()); // 打开链接 conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行查询 // 实例化Statement对象 stmt = conn.createStatement(); String sql = "SELECT " + key + " FROM usertest"; ResultSet rs = stmt.executeQuery(sql); // 将数据添加进集合中 while(rs.next()){ array.add(rs.getString(key)); } // 完成后关闭 rs.close(); stmt.close(); conn.close(); return array; }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); return array; }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); return array; }finally{ // 关闭资源 try{ if(stmt!=null) { stmt.close(); return array; } }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) { conn.close(); return array; } }catch(SQLException se){ se.printStackTrace(); return array; } } } }
package com.ffyc.webback.servlet; import com.ffyc.webback.Dao.LoginDao; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doGet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // System.out.println("doPost"); // 根据 列 得到数据库的表的各列元素的集合 List<String> names = LoginDao.getElementArray("name"); List<String> passwords = LoginDao.getElementArray("password"); // 得到表单数据 String name = req.getParameter("account"); String password = req.getParameter("psw"); // 判断表单数据-账户,是否在数据库中存在 if(names.contains(name)) { System.out.println("账户存在"); } else { System.out.println("账户不存在"); return; } // 账户正确,得到数据库中,账户对应的密码索引 int index = -1; for (int i = 0; i < names.size(); i++) { if (name.equals(names.get(i))) { index = i; } } // 判断密码是否正确 if ( index == -1 || !( password.equals( passwords.get(index) ) ) ) { System.out.println("密码不正确"); return; } else { System.out.println("密码正确,登陆成功"); } } }
上述代码将数据库的数据拿到后端服务器中,在服务器创建了临时列表存储,消耗资源大。优化代码,直接使用SQL查询语句在数据库中查询。
package com.ffyc.webback.Dao; import com.ffyc.webback.model.User; import java.sql.*; public class LoginDao { static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/feifan_test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"; // 数据库的用户名与密码,需要根据自己的设置 static final String USER = "root"; static final String PASS = "root"; public static User getUserObject(String name, String password){ Connection conn = null; Statement stmt = null; User user = null; try{ // 打开链接 Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行查询 // 实例化Statement对象 stmt = conn.createStatement(); PreparedStatement ps = conn.prepareStatement("SELECT * FROM usertest WHERE name = ? AND password = ?"); ps.setObject(1,name); ps.setObject(2,password); ResultSet rs = ps.executeQuery(); // 将数据添加进集合中 while(rs.next()){ user = new User(); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); } // 完成后关闭 rs.close(); stmt.close(); conn.close(); return user; }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); return user; }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); return user; }finally{ // 关闭资源 try{ if(stmt!=null) { stmt.close(); return user; } }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) { conn.close(); return user; } }catch(SQLException se){ se.printStackTrace(); return user; } } } }
package com.ffyc.webback.servlet; import com.ffyc.webback.Dao.LoginDao; import com.ffyc.webback.model.User; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // System.out.println("doGet"); resp.setContentType("text/html;charset=utf-8"); // 得到表单数据 String name = req.getParameter("account_name"); String password = req.getParameter("password_name"); User user = LoginDao.getUserObject(name, password); if (user == null) { resp.getWriter().println("账户或密码错误"); } else { resp.getWriter().println("登陆成功"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // System.out.println("doPost"); resp.setContentType("text/html;charset=utf-8"); // 得到表单数据 String name = req.getParameter("account_name"); String password = req.getParameter("password_name"); User user = LoginDao.getUserObject(name, password); if (user == null) { resp.getWriter().println("账户或密码错误"); } else { resp.getWriter().println("登陆成功"); } } }
在部署web服务,使用class.forName创建JDBC驱动时,必须将JDBC驱动添加到项目Web下的lib目录下。