Servlet登陸小案例

需求:
登陸功能 
登陸頁面輸入用戶名和密碼, 到數據庫進行驗證 ,若是成功跳轉到success.html頁面,失敗跳轉到error.html頁面
數據庫 mysql,數據表 t_user表【表中的字段 :name 用戶名,pwd 密碼】
實現:
mysql 存儲數據建表 
jdbc操做java代碼鏈接查詢數據庫裏對應的字段
servlet將 html和java鏈接起來,用login來登陸轉發到成功或者失敗頁面。
實現步驟:
jdbc 
依賴 jar包,數據庫鏈接的util DBUtil數據庫鏈接工具類
mysql 鏈接
db.properties 數據庫鏈接配置
核心代碼實現:(DAO層)
sql語句 查詢:String sql = "select * from t_user  where name=? and pwd =? ";
建立一個實體類和數據庫表對應,dao層 用戶名和密碼驗證,返回一個結果 對象 
servlet調用DAO層:若是用戶存在 ,不爲空,跳轉到ok.html頁面 ;若是不存在,對象爲空, 登陸失敗 error.html
css

前臺頁面:
login.html【登陸界面】html

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <title>login.html</title>
 5     <meta charset="utf-8">
 6     <meta name="keywords" content="keyword1,keyword2,keyword3">
 7     <meta name="description" content="this is my page">
 8     <meta name="content-type" content="text/html; charset=UTF-8">
 9     
10     <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
11 
12   </head>
13   
14   <body>
15       <form action="UserLogin">
16           用戶名:<input type="text" name="uname" id="uname" /><br>
17           密碼:<input type="password" name="pwd" id="pwd" /><br>
18           <input value="登陸" type="submit"/>
19       </form>
20   </body>
21 </html>
View Code

success.html【登陸成功界面】前端

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <title>success.html</title>
 5     <meta charset="utf-8">
 6     <meta name="keywords" content="keyword1,keyword2,keyword3">
 7     <meta name="description" content="this is my page">
 8     <meta name="content-type" content="text/html; charset=UTF-8">
 9     
10     <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
11 
12   </head>
13   
14   <body>
15     This is 登陸成功  page.看到女神<br>
16     <div>
17     <img src="imges/success.jpg"  width="800px" height="500px"/>
18     </div>
19   </body>
20 </html>
View Code

error.html【登陸失敗界面】java

 1 <!DOCTYPE html>
 2 <html>
 3   <head>
 4     <title>error.html</title>
 5     <meta charset="utf-8">
 6     <meta name="keywords" content="keyword1,keyword2,keyword3">
 7     <meta name="description" content="this is my page">
 8     <meta name="content-type" content="text/html; charset=UTF-8">
 9     
10     <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
11 
12   </head>
13   
14   <body>
15     This is 登陸失敗  page.一直在轉悠轉悠 <br>
16     <div>
17         <img src="imges/error.gif" />
18     </div>
19   </body>
20 </html>
View Code

entity層【實體類】mysql

 1 package boom.servlet.entity;
 2 /**
 3  * 實體類
 4  * @author Administrator
 5  *
 6  */
 7 public class T_user {
 8     // 對應着數據庫表的字段
 9     private int id;
10     private String name;
11     private String pwd;
12     // 無參構造方法
13     public T_user() {
14     }
15     // 有參構造方法
16     public T_user(int id, String name, String pwd) {
17         super();
18         this.id = id;
19         this.name = name;
20         this.pwd = pwd;
21     }
22     // getter setter
23     public int getId() {
24         return id;
25     }
26     public void setId(int id) {
27         this.id = id;
28     }
29     public String getName() {
30         return name;
31     }
32     public void setName(String name) {
33         this.name = name;
34     }
35     public String getPwd() {
36         return pwd;
37     }
38     public void setPwd(String pwd) {
39         this.pwd = pwd;
40     }
41     // 重寫toString
42     @Override
43     public String toString() {
44         return "T_user [id=" + id + ", name=" + name + ", pwd=" + pwd + "]";
45     }
46     
47 }
View Code

util層【封裝的JDBC數據庫鏈接】sql

  1 package boom.servlet.util;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.sql.Connection;
  6 import java.sql.DriverManager;
  7 import java.sql.PreparedStatement;
  8 import java.sql.ResultSet;
  9 import java.sql.SQLException;
 10 import java.sql.Statement;
 11 import java.util.Properties;
 12 /**
 13  * 鏈接數據庫的工具類
 14  * @author Administrator
 15  *
 16  */
 17 public class DBUtil {
 18     private static String driver;
 19     private static String url;
 20     private static String username;
 21     private static String password;
 22 
 23     static {
 24         // 建立properties對象獲取屬性文件的內容
 25         Properties p = new Properties();
 26         // 獲取屬性配置文件的讀取流對象
 27         InputStream is = DBUtil.class.getResourceAsStream("/db.properties");
 28         try {
 29             // 加載屬性配置文件
 30             p.load(is);
 31             // 獲取jdbc參數
 32             driver = p.getProperty("driver");
 33             url = p.getProperty("url");
 34             username = p.getProperty("username");
 35             password = p.getProperty("password");
 36             // 加載驅動
 37             Class.forName(driver);
 38         } catch (IOException e) {
 39             e.printStackTrace();
 40         } catch (ClassNotFoundException e) {
 41             // TODO Auto-generated catch block
 42             e.printStackTrace();
 43         }
 44     }
 45 
 46     // 獲取Connection對象
 47     public static Connection getConnection() {
 48         Connection conn = null;
 49         try {
 50             conn = DriverManager.getConnection(url, username, password);
 51         } catch (SQLException e) {
 52             e.printStackTrace();
 53         }
 54         return conn;
 55     }
 56 
 57     // 封裝獲取PreparedStatement對象
 58     public static PreparedStatement getPreparedStatement(String sql,
 59             Connection conn) {
 60 
 61         PreparedStatement ps = null;
 62         try {
 63             ps = conn.prepareStatement(sql);
 64         } catch (SQLException e) {
 65             // TODO Auto-generated catch block
 66             e.printStackTrace();
 67         }
 68         return ps;
 69 
 70     }
 71 
 72     // 封裝獲取Statement對象
 73     public static Statement getStatement(Connection conn) {
 74         Statement stmt = null;
 75         try {
 76             stmt = conn.createStatement();
 77         } catch (SQLException e) {
 78             e.printStackTrace();
 79         }
 80         return stmt;
 81 
 82     }
 83 
 84     // 關閉資源
 85     //父類能夠調用 子類繼承過的父類方法
 86     public static void closeAll(ResultSet rs, Statement ps, Connection conn) {
 87         try {
 88             if(rs!=null ){
 89                 rs.close();
 90             }
 91         } catch (SQLException e1) {
 92             e1.printStackTrace();
 93         }
 94         try {
 95             if(ps!=null ){
 96                 ps.close();
 97             }
 98         } catch (SQLException e) {
 99                 e.printStackTrace();
100         }
101         try {
102             if(conn!=null){
103                 conn.close();
104             }
105         } catch (SQLException e) {
106             e.printStackTrace();
107         }
108     }
109     // 封裝DML
110     public static int executeDML(String sql, Object... objs) {
111         // 建立鏈接對象
112         Connection conn = getConnection();
113         // 建立sql命令對象
114         PreparedStatement ps = DBUtil.getPreparedStatement(sql, conn);
115         // 給佔位符賦值
116         try {
117             conn.setAutoCommit(false);
118             for (int i = 0; i < objs.length; i++) {
119                 ps.setObject(i + 1, objs[i]);
120             }
121             int i = ps.executeUpdate();
122             conn.commit();
123             return i;
124         } catch (Exception e) {
125             try {
126                 conn.rollback();
127             } catch (SQLException e1) {
128                 // TODO Auto-generated catch block
129                 e1.printStackTrace();
130             }
131         } finally {
132             // 關閉資源
133             DBUtil.closeAll(null, ps, conn);
134         }
135         // 返回結果
136         return -1;
137     }
138     // 測試數據庫是否鏈接成功
139     public static void main(String[] args) {
140         Connection conn = DBUtil.getConnection();
141         System.out.println(conn);
142     }
143 }
View Code

dao層【user實現類】數據庫

 1 package boom.servlet.dao;
 2 
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 
 8 import boom.servlet.entity.T_user;
 9 import boom.servlet.util.DBUtil;
10 
11 /**
12  * 登陸查詢實現類
13  * @author Administrator
14  *select * from t_user where name='admin' and pwd='admin'
15  */
16 public class UserDaoImpl {
17     // 返回對象
18     public T_user getUser(String name,String pwd){
19         String sql = "select * from t_user  where name=? and pwd =? ";
20         Connection conn = null;
21         PreparedStatement  ps = null;
22         ResultSet rs = null;
23         T_user user=  null;
24         //1.建立鏈接
25         conn = DBUtil.getConnection();
26         try {
27               //2.獲取預處理塊對象  preparestatement
28               ps = conn.prepareStatement(sql);
29               //3.綁定參數
30               ps.setString(1, name);
31               ps.setString(2, pwd);
32               //4.執行SQL語句  5.獲取結果集
33                rs = ps.executeQuery();
34               //6.遍歷結果集存放到 user對象中
35                while(rs.next()){
36                    int id = rs.getInt("id");
37                    String name2 = rs.getString("name");
38                    String pwd2 = rs.getString("pwd");
39                    //將數據放到對象中
40                    user = new T_user(id,name2,pwd2);
41                }
42         } catch (SQLException e) {
43             e.printStackTrace();
44         }finally{
45             //7.關閉資源
46             DBUtil.closeAll(rs, ps, conn);
47         }
48         return user;
49     }
50 }
View Code

servlet層【獲取前端頁面登陸驗證】ide

 1 package boom.servlet.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import boom.servlet.dao.UserDaoImpl;
11 import boom.servlet.entity.T_user;
12 /**
13  * 獲取前端頁面登陸驗證
14  * @author Administrator
15  *
16  */
17 public class UserLogin extends HttpServlet {
18     @Override
19     protected void service(HttpServletRequest request,
20             HttpServletResponse response) throws ServletException, IOException {
21         // 一、獲取login用戶提交的數據【帳戶,密碼】
22         String uname = request.getParameter("uname");
23         String pwd = request.getParameter("pwd");
24         // 二、調用業務邏輯層。簡化後調用dao層
25         UserDaoImpl daoImpl = new UserDaoImpl();
26         T_user user = daoImpl.getUser(uname, pwd);
27         String path = "/login.html";
28         if (user != null) {
29             path = "/success.html";
30         } else {
31             path = "/error.html";
32         }
33         // 3 根據dao的查詢結果 ,跳轉到成功或失敗頁面
34         request.getRequestDispatcher(path).forward(request, response);
35 
36     }
37 }
View Code

test層【測試dao層是否鏈接成功】工具

 1 package boom.servlet.test;
 2 
 3 import boom.servlet.dao.UserDaoImpl;
 4 import boom.servlet.entity.T_user;
 5 
 6 /**
 7  * 測試dao層
 8  * @author Administrator
 9  *
10  */
11 public class TestUserDao {
12     public static void main(String[] args) {
13         UserDaoImpl daoImpl = new UserDaoImpl();
14         T_user user = daoImpl.getUser("boom", "123");
15         if(user != null){
16             System.out.println("登陸成功");
17         }else{
18             System.out.println("登陸失敗");
19         }
20     }
21 }
View Code

數據庫配置文件【db.properties】

演示界面:



測試

相關文章
相關標籤/搜索