jsp 實慄 jsp + jdbc 登入
jsp 實慄 jsp + jdbc 實現登入
實現思路
一個表單頁,輸入使用者登入和密碼,然後資訊提交到jsp頁面進行驗證,如果可以伺服器跳轉到登入成功頁,失敗,跳轉到錯誤頁
跳轉的時候視窗的URL地址會發生變化
程式碼如下
編寫登入程式碼
登入
<!DOCTYPE html> <html lang="zh_CN"> <head> <meta charset="UTF-8"> <title>登入</title> </head> <body> <h1>登入操作</h1> <form action="login_check.jsp" method="post"> <h1>使用者登入</h1> <p> 登入id <input type="text" name="id"/> </p> <p> 登入密碼 <input type="password" name="password"/> </p> <input type="submit" value="登入"/> <input type="reset" value="重置"/> </form> </body> </html>
登入處理
<%@ page import="java.sql.*" %> <%-- Created by IntelliJ IDEA. User: ming Date: 19-3-9 Time: 下午5:50 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%! // 資料庫驅動程式 public static final String DBDRIVER = "com.mysql.cj.jdbc.Driver"; // 資料庫連線地址 public static final String DBURL = "jdbc:mysql://47.94.95.84:32786/test"; // 使用者名稱 public static final String DBUSER = "root"; // 密碼 public static final String DBPASS = "ABCcba20170607"; %> <% // 連線物件 Connection connection = null; // 操作 PreparedStatement preparedStatement = null; // 結果 ResultSet resultSet = null; // 標誌位 boolean falge = false; // 使用者真實姓名 String name = null; %> <% try{ Class.forName(DBDRIVER); // 獲得連線 connection = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 編寫sql驗證ID 密碼 String sql = "SELECT name FROM user WHERE userid = ? AND password = ?"; // 例項化操作物件 preparedStatement = connection.prepareStatement(sql); // 設定查詢內容 preparedStatement.setString(1, request.getParameter("id")); preparedStatement.setString(2, request.getParameter("password")); // 執行查詢 resultSet = preparedStatement.executeQuery(); // 如果可以查詢到,表示合法使用者 if(resultSet.next()){ name = resultSet.getString(1); // 修改標誌位 falge = true; } }catch (Exception e){ e.printStackTrace(); }finally { try{ resultSet.close(); preparedStatement.close(); connection.close(); }catch (Exception e){ e.printStackTrace(); } } %> <% // 登入成功 if(falge){ // 進行伺服器端跳轉 %> <jsp:forward page="./login_sucess.jsp"> <jsp:param name="uname" value="<%=name%>"/> </jsp:forward> <% }else{ %> <jsp:forward page="./login_failure.html"/> <% } %> </body> </html>
登入完成
<%-- Created by IntelliJ IDEA. User: ming Date: 19-3-9 Time: 下午10:22 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>登入成功</h1> <%=request.getParameter("uname")%> </body> </html>
登入失敗
<%-- Created by IntelliJ IDEA. User: ming Date: 19-3-9 Time: 下午10:22 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>登入成功</h1> <%=request.getParameter("uname")%> </body> </html>
效果演示
登入介面