DAO設計模式簡介(轉)


http://blog.csdn.net/thystar/article/details/41786763

 

DAO(Data Access Object,數據訪問對象),主要的功能是用於進行數據操作的,在程序的標准開發框架中屬於數據層的操作。

數據開發結構:

資源層是數據庫的操作層,里面可以進行各種數據庫的存儲,但是這些數據存儲的時候肯定是依靠SQL語句,數據層通過一個專門的數據庫組件完成對數據庫的操作

業務層是整個項目的核心

 

DAO組成

DatabaseConnection:專門負責數據庫打開與關閉操作的類

VO:主要由屬性,setter, getter方法組成,VO類中的屬性與表中的字段相對應,每一個VO類的對象都表示表中的每一條記錄;

DAO:主要定義操作的接口,定義一系列數據庫的原子性操作,例如增刪改查等;

Impl: DAO接口的真實實現類,主要完成具體數據庫操作,但不負責數據庫的打開和關閉;

Proxy:代理實現類,主要完成數據庫的打開和關閉並且調用真實實現類對象的操作;

Factory: 工廠類,通過工廠類取得一個DAO的實例化對象。

 

對於包的命名:

在使用DAO時對包有嚴格的命名

 

  • 數據庫連接: xxx.dbc.DatabaseConnection
  • DAO接口: xxx.dao.IXxxDAO
  • DAO接口真實實現類:xxx.dao.impl.XxxDAOImpl
  • DAO接口代理實現類:xxx.dao.proxy.XxxDAOProxy
  • VO類: xxx.vo.Xxx, VO命名要與表的命名一致
  • 工廠類:xxx.factory.DAOFactory.

 

用DAO重新寫登陸頁面:

所需要的文件:這里直接使用MVC模式開發,使用myeclipse 10。

 

數據庫腳本:

 

[sql]  view plain  copy
 
  1. /*=============刪除數據庫=============*/  
  2. DROP DATABASE IF EXISTS usr;  
  3. /*=============創建數據庫=============*/  
  4. CREATE DATABASE usr;  
  5. /*=============使用數據庫=============*/  
  6. USE usr;  
  7. /*=============刪除數據庫表===========*/  
  8. DROP TABLE IF EXISTS login;  
  9. /*=============創建數據庫表===========*/  
  10. CREATE TABLE login(  
  11.     userid          VARCHAR(30)         PRIMARY KEY,  
  12.     name            VARCHAR(30)         NOT NULL,  
  13.     password        VARCHAR(32)         NOT NULL  
  14. );  
  15.   
  16. INSERT INTO login(userid, name, password)VALUES('admin', 'admin', 'admin');  


1.定義vo類,vo類定義了數據的屬性,及相應的setter,getter方法。

定義User類 :User.java -------- package org.thystar.mvcdemo.vo.User.

 

[java]  view plain  copy
 
  1. /** 
  2.  * vo層 
  3.  */  
  4. package org.thystar.mvcdemo.vo;  
  5.   
  6. /** 
  7.  *  
  8.  * 定義用戶類 
  9.  */  
  10. public class User {  
  11.     private String userid;       //用戶ID  
  12.     private String name;         //用戶名  
  13.     private String password;     //密碼  
  14.     public String getUserid() {  
  15.         return userid;  
  16.     }  
  17.     public void setUserid(String userid) {  
  18.         this.userid = userid;  
  19.     }  
  20.     public String getName() {  
  21.         return name;  
  22.     }  
  23.     public void setName(String name) {  
  24.         this.name = name;  
  25.     }  
  26.     public String getPassword() {  
  27.         return password;  
  28.     }  
  29.     public void setPassword(String password) {  
  30.         this.password = password;  
  31.     }  
  32.       
  33. }  


2. 定義數據庫連接類,這個類只負責連接數據庫:

定義DataBaseConnection類 DatabaseConnection.java ------------package org.thystar.mvcdemo.dbc.DatabaseConnection;

 

[java]  view plain  copy
 
  1. package org.thystar.mvcdemo.dbc;  
  2.   
  3. import java.sql.*;  
  4. /** 
  5.  *  
  6.  * 連接數據庫 
  7.  * 
  8.  */  
  9. public class DatabaseConnection {  
  10.     // 定義數據庫驅動程序  
  11.     private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";    
  12.     // 數據庫連接地址  
  13.     private static final String DBURL = "jdbc:mysql://localhost:3306/usr";  
  14.     private static final String DBUSER = "root";            // 數據庫連接用戶名  
  15.     private static final String DBPASSWORD = "mysqladmin";  // 數據庫連接密碼  
  16.       
  17.     private Connection conn = null;      //聲明數據庫連接對象  
  18.     public DatabaseConnection() throws Exception{     //構造函數  
  19.         try{  
  20.             Class.forName(DBDRIVER);   // 加載驅動程序  
  21.             this.conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);  // 取得數據庫連接  
  22.         }catch(Exception e){  
  23.             throw e;  
  24.         }  
  25.     }  
  26.     public Connection getConnection() { //取得數據庫連接  
  27.         return this.conn;  
  28.     }  
  29.     public void close() throws Exception { // 關閉數據庫操作  
  30.         if(this.conn != null){          // 避免NullPointerException  
  31.             try{  
  32.                 this.conn.close();       // 關閉數據庫  
  33.             }catch(Exception e){  
  34.                 throw e;               // 拋出異常  
  35.             }  
  36.         }  
  37.     }     
  38. }  


3 . 定義數據庫操作接口,定義數據庫操作的方法:

定義IUserDAO接口,IUserDAO.java --------- package org.thystar.mvcdemo.dao.IUserDAO

 

[java]  view plain  copy
 
  1. package org.thystar.mvcdemo.dao;  
  2. // 在這個操作中要導入vo包。  
  3. import org.thystar.mvcdemo.vo.*;  
  4. /** 
  5.  *  
  6.  * 數據庫操作接口 
  7.  * 
  8.  */  
  9. public interface IUserDAO {  
  10.     /** 
  11.      * 用戶登錄驗證 
  12.      * @param user 傳入vo對象 
  13.      * @return 驗證操作結果 
  14.      * @throws Exception 
  15.      */  
  16.     public boolean findLogin(User user) throws Exception;  
  17. }  


4. 定義DAO實現類,實現接口中定義的方法

定義UserDAOImpl類, UserDAOImpl.java ---------package org.thystar.mvcdemo.dao.impl.UserDAOImpl

 

[java]  view plain  copy
 
  1. package org.thystar.mvcdemo.dao.impl;  
  2.   
  3. import java.sql.*;  
  4. import org.thystar.mvcdemo.dao.IUserDAO;  
  5. import org.thystar.mvcdemo.vo.User;  
  6. /** 
  7.  *  
  8.  * DAO實現類,實現方法,但不負責數據庫的具體連接 
  9.  * 
  10.  */  
  11. public class UserDAOImpl implements IUserDAO{  
  12.     private Connection conn = null;         //定義數據庫的連接對象  
  13.     private PreparedStatement pstmt = null; //定義數據庫操作對象  
  14.     public UserDAOImpl(Connection conn){    // 構造方法,設置數據庫連接  
  15.         this.conn = conn;  
  16.     }  
  17.     /** 
  18.      * 具體操作方法:查詢 
  19.      */  
  20.     public boolean findLogin(User user) throws Exception{  
  21.         boolean flag = false;                //定義標志位  
  22.         try{  
  23.             String sql = "SELECT name FROM login WHERE userid = ? AND password = ?";  
  24.             this.pstmt = this.conn.prepareStatement(sql);     // 實例化操作  
  25.             this.pstmt.setString(1, user.getUserid());        // 設置用戶id  
  26.             this.pstmt.setString(2, user.getPassword());      // 設置password  
  27.             ResultSet rs = this.pstmt.executeQuery();         // 取得查詢結果  
  28.             if(rs.next()){  
  29.                 user.setName(rs.getString(1));                //取得姓名  
  30.                 flag = true;  
  31.             }  
  32.         }catch(Exception e){  
  33.             throw e;  
  34.         }  
  35.         return flag;  
  36.     }  
  37. }  

可以看出,在真實的數據庫的實現類中,沒有處理數據庫打開和關閉的操作,只是通過構造方法取得了數據庫的連接,真正的負責打開和關閉的操作由代理類實現

5.代理(proxy)類實現:負責數據庫的打開和關閉及調用真實實現類對象操作:

定義UserDAOProxy implements IUserDAO,UserDAOProxy.java ------------package org.thystar.mvcdemo.dao.proxy.UserDAOProxy

 

[java]  view plain  copy
 
  1. package org.thystar.mvcdemo.dao.proxy;  
  2. /** 
  3.  * 代理類,要找到真實主題 
  4.  */  
  5. import org.thystar.mvcdemo.dao.IUserDAO;  
  6. import org.thystar.mvcdemo.dbc.DatabaseConnection;  
  7. import org.thystar.mvcdemo.dao.impl.UserDAOImpl;  
  8. import org.thystar.mvcdemo.vo.User;  
  9.   
  10. public class UserDAOProxy implements IUserDAO {  
  11.     private DatabaseConnection dbc = null;  
  12.     private IUserDAO dao = null;  
  13.     public UserDAOProxy() {       //構造方法,實例化連接,同時實例化dao對象  
  14.         try {  
  15.             this.dbc = new DatabaseConnection();    // 連接數據庫  
  16.         } catch (Exception e) {  
  17.             // TODO Auto-generated catch block  
  18.             e.printStackTrace();  
  19.         }  
  20.         this.dao = new UserDAOImpl(this.dbc.getConnection());  //實例化真實主題類  
  21.     }  
  22.     public boolean findLogin(User user) throws Exception{  // 實現接口中的方法。  
  23.         boolean flag = false; //定義標志位  
  24.         try{  
  25.             flag = this.dao.findLogin(user);  // 調用真實主題  
  26.         }catch(Exception e){                    
  27.             throw e;                           //向上拋出異常  
  28.         }finally{  
  29.             this.dbc.close();  
  30.         }  
  31.         return flag; //返回標記  
  32.     }  
  33.       
  34. }  


6. 工廠類的實現: 取得DAO實例

定義DAOFactory類, DAOFactory.java --------------package org.thystar.mvcdemo.factory.DAOFactory

 

[java]  view plain  copy
 
  1. package org.thystar.mvcdemo.factory;  
  2.   
  3. import org.thystar.mvcdemo.dao.IUserDAO;  
  4. import org.thystar.mvcdemo.dao.proxy.UserDAOProxy;  
  5. /** 
  6.  *  
  7.  * 工長類 
  8.  * 
  9.  */  
  10. public class DAOFactory {  
  11.     public static IUserDAO getIUserDAOInstance(){      // 取得DAO實例  
  12.         return new UserDAOProxy();       // 返回代理實例  
  13.     }  
  14. }  

工廠類的功能就是直接返回DAO接口的實例化對象,以后客戶端直接通過工廠類就可以取得DAO接口的實例化對象

到這里,數據層的部分就完成了,下面開始定義Servlet/jsp部分,也就是顯示層,進行頁面的顯示

7 .定義Servlet:

LoginServlet.java

 

[java]  view plain  copy
 
  1. /** 
  2.  * 定義Servlet 
  3.  */  
  4. package org.thystar.mvcdemo.servlet;  
  5.   
  6. import java.io.IOException;  
  7. import java.io.PrintWriter;  
  8. import java.util.ArrayList;  
  9. import java.util.List;  
  10.   
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.http.HttpServlet;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. import javax.servlet.http.HttpServletResponse;  
  15.   
  16. import org.thystar.mvcdemo.factory.DAOFactory;  
  17. import org.thystar.mvcdemo.vo.User;  
  18.   
  19. public class LoginServlet extends HttpServlet {  
  20.   
  21.     private static final long serialVersionUID = 1L;  
  22.   
  23.     /** 
  24.      * The doGet method of the servlet. <br> 
  25.      * 
  26.      * This method is called when a form has its tag value method equals to get. 
  27.      *  
  28.      * @param request the request send by the client to the server 
  29.      * @param response the response send by the server to the client 
  30.      * @throws ServletException if an error occurred 
  31.      * @throws IOException if an error occurred 
  32.      */  
  33.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  34.             throws ServletException, IOException {  
  35.   
  36.         String path = "login.jsp";             
  37.         String userid = request.getParameter("userid"); //接收userid的內容  
  38.         String userpass = request.getParameter("userpass"); //接收userpass的內容  
  39.         List<String> info = new ArrayList<String>();   // 保存返回信息  
  40.         //判斷輸入為空的情況  
  41.         if(userid == null || "".equals(userid)){      
  42.             info.add("用戶id不能為空");  
  43.         }  
  44.         if(userpass == null || "".equals(userpass)){  
  45.             info.add("密碼不能為空");  
  46.         }  
  47.         //用戶名密碼驗證通過  
  48.         if(info.size() == 0){  
  49.             User user = new User();      //實例化vo  
  50.             user.setUserid(userid);      //設置userid  
  51.             user.setPassword(userpass);  //設置userpass  
  52.             try {  
  53.                 if(DAOFactory.getIUserDAOInstance().findLogin(user)){ //驗證通過  
  54.                     info.add("通過驗證" + user.getName() + "已登錄");  
  55.                 }else{  
  56.                     info.add("登錄失敗");  
  57.                 }  
  58.             } catch (Exception e) {  
  59.                 // TODO: handle exception  
  60.                 e.printStackTrace();  
  61.             }     
  62.         }  
  63.         request.setAttribute("info", info);     
  64.         request.getRequestDispatcher(path).forward(request, response); //跳轉  
  65.     }  
  66.   
  67.     /** 
  68.      * The doPost method of the servlet. <br> 
  69.      * 
  70.      * This method is called when a form has its tag value method equals to post. 
  71.      *  
  72.      * @param request the request send by the client to the server 
  73.      * @param response the response send by the server to the client 
  74.      * @throws ServletException if an error occurred 
  75.      * @throws IOException if an error occurred 
  76.      */  
  77.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  78.             throws ServletException, IOException {  
  79.   
  80.         this.doGet(request, response);  // 調用doGet操作  
  81.     }  
  82.   
  83. }  


8. 登陸頁 

login.jsp

 

[javascript]  view plain  copy
 
  1. <%@ page contentType = "text/html" pageEncoding="GBK" import = "java.util.*"%>  
  2.   
  3. <html>  
  4.   <head>  
  5.       
  6.     <title>www.thystar.com</title>  
  7.     <script language = "JavaScript">  
  8.       
  9.         function validate(f){  
  10.             if(!(/^\w{1,15}$/.test(f.userid.value))){  
  11.                 alert("用戶ID必須是1~15位");  
  12.                 f.userid.focus();  
  13.                 return false;  
  14.             }  
  15.             if(!(/^\w{1,15}$/.test(f.userpass.value))){  
  16.                 alert("密碼必須是1~15位");  
  17.                 f.userpass.focus();  
  18.                 return false;  
  19.             }  
  20.             return true;  
  21.         }  
  22.     </script>  
  23.   
  24.   </head>  
  25.     
  26.   <body>  
  27.     <h2>用戶登錄</h2>  
  28.      <%  
  29.         request.setCharacterEncoding("GBK");  
  30.      %>  
  31.      <%  
  32.         List<String> info=(List<String>)request.getAttribute("info");  
  33.         if(info != null){  
  34.             Iterator<String> iter = info.iterator();  
  35.             while(iter.hasNext()){  
  36.      %>  
  37.                 <h4><%= iter.next() %></h4>  
  38.      <%  
  39.             }  
  40.         }  
  41.      %>  
  42.      <form action="LoginServlet" method="post" onSubmit = "validate(this)">  
  43.        
  44.         用戶ID: <input type = "text" name = "userid"><br>  
  45.         密  碼:<input type = "password" name="userpass"><br>  
  46.         <input type = "submit" value = "登錄">  
  47.         <input type = "reset" value = "重置">  
  48.      </form>  
  49.   </body>  
  50. </html>  


結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM