2015年12月22日 星期二

JAVA SL-314_12/20

Date: 12/20
/================================================/

DAO(Data Access Object)資料存取物件
主要的功能是資料操作,屬於資料層的操作

client   →  JSP/Servlet  →  BO  →  DAO  →  Database
客戶層        顯示層          業務層     資料層       資源層

client →  B/S開發架構,大都以Browser進行存取
顯示層 → 以JSP/Servlet進行頁面效果的顯示
Business Object→ 將多個最小的DAO進行組合變成一個業務邏輯--> BO
DAO→ 提拱多個最小性的DAO操作,例如新增刪除、修改

/================================================/

DAO → 由以下幾個部分組成:

Database Connection → 負責資料庫的開啟與關閉 (xxx.dbc.DatabaseConnection)
VO → 主要是屬性,setter、getter方法組成,與欄位相對應,每一個VO的組成都對應到一條記錄 (like JavaBean)
DAO → 定義操作的介面,新增、刪除、修改、按ID查詢等 (xxx.dao.ImplDAO)
Impl → DAO介面的真實實歸類別,完成實際的資料庫操作不負責開啟和關閉(xxx.dao.xxxImplDAO)
Proxy →  代理實現類別,完成資料庫的開啟和關閉 (xxx.dao.xxxDAOProxy)
Factory → 工廠類別,透過他取得一個DAO產生的實體物件 (xxx.factor.DAOFactory)

/================================================/
組成: 註冊系統 --> 將資料存到架設好的mySQL建表
1. index.jsp、emp_list.jsp、insert_success.jsp
2. com.demo => DatabaseConnection.java、Emp.java、IEmpDAO.java、IEmpDAOImpl.java、EmpDAOProxy.java、DAOFactory.java
3. com.dome.dbc => DatabaseConnection.java、MySQLDatabaseConnection.java
##ReadMore##
//index.jsp

<%@ page language="java" import="java.util.*" import="java.sql.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
       
    <title>新增員工</title>
 
  </head>
  
  <body  bgcolor="silver">
    <center>
    <h2><font color="blue" size="7">【南臺科大-員工註冊系統】</h2></font>
    <form action="insert_success.jsp" method="post" >
     <font size="5">●員工編號:</font><input type="text" name="empno"><br>
     <font size="5">●員工姓名:</font><input type="text" name="ename"><br>
  <font size="5">●員工職位:</font><input type="text" name="job"><br>
  <font size="5">●到職日期:</font><input type="text" name="hiredate"><br>
  <font size="5">●基本薪資:</font><input type="text" name="sal"><br>
  <input type="submit" value="註冊">
  <input type="reset" value="重設">
    </form>
    </center>
  </body>
</html>

//insert_success.jsp
<%@ page language="java" import="java.util.*" import="java.util.Date" import="java.sql.*" pageEncoding="UTF-8"%>
<%@ page import="com.demo.*" %>
<%@ page import="java.text.*" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'insert_success.jsp' starting page</title>
    
  </head>
  <% request.setCharacterEncoding("UTF-8"); %>
  <body>
<%
 Emp emp=new Emp();
 emp.setEmpno(Integer.parseInt(request.getParameter("empno")));
 emp.setEname(request.getParameter("ename"));
 emp.setJob(request.getParameter("job"));
 emp.setHiredate(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("hiredate")));
 emp.setSal(Float.parseFloat(request.getParameter("sal")));
 try{
  if(DAOFactory.getIEmpDAOInstance().doCreate(emp)){
%>
  <h3>新增成功</h3>
<%
  }else{
%>
  <h3>新增失敗</h3>
<%
  }
%>
<%
 }catch(Exception e){
  e.printStackTrace();
 }
%>
  </body>
</html>

//emp_list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="BIG5"%>
<%@ page import="java.util.*,com.demo.*"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    
    <title>My JSP 'emp_list.jsp' starting page</title>
    

  </head>
 <%
 request.setCharacterEncoding("UTF-8");
%>
<body>
 <%
  try {
   String keyword = request.getParameter("kw");//接收查詢關鍵字
   if (keyword == null) {//判斷是否有傳遞參數
    keyword = ""; // 如果沒有查詢關鍵字,則查詢全部
   }
   List<Emp> all = DAOFactory.getIEmpDAOInstance().findAll(keyword);
   Iterator<Emp> iter = all.iterator();//產生實體Iterator物件
 %>
 <center>
  <form action="emp_list.jsp" method="post">
   請輸入查詢關鍵字:<input type="text" name="kw"> <input type="submit"
    value="查詢">
  </form>
  <table border="1" width="80%">
   <tr>
    <td>僱員編號</td>
    <td>僱員姓名</td>
    <td>僱員工作</td>
    <td>僱傭日期</td>
    <td>基本薪水</td>
   </tr>
   <%
    while (iter.hasNext()) {
      Emp emp = iter.next();
   %>
   <tr>
    <td><%=emp.getEmpno()%></td>
    <td><%=emp.getEname()%></td>
    <td><%=emp.getJob()%></td>
    <td><%=emp.getHiredate()%></td>
    <td><%=emp.getSal()%></td>
   </tr>
   <%
    }
   %>
  </table>
 </center>
 <%
  } catch (Exception e) {
   e.printStackTrace();
  }
 %>
</body>
</html>

//DatabaseConnection.java
package com.demo;

import java.sql.Connection;
import java.sql.DriverManager;

public class DatabaseConnection {
 public static final String DBDRIVER="com.mysql.jdbc.Driver"; 
 public static final String DBURL="jdbc:mysql://localhost:3306/people"; 
 public static final String DBUSER="root"; 
 public static final String DBPASSWORD="abc123";
 private Connection conn;
 public DatabaseConnection()throws Exception{
  Class.forName(DBDRIVER);
  this.conn=DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
 }
 public Connection getConn(){
  return this.conn;
 }
 public void close() throws Exception{
  if(this.conn!=null){
   try{
    this.conn.close();
   }catch(Exception e){
    throw e;
   }
  }
 }
 
 
}

//Emp.java
package com.demo;

import java.util.Date;

public class Emp {
 private int empno;
 private String ename;
 private String job;
 private Date hiredate;
 private float sal;
 public int getEmpno() {
  return empno;
 }
 public void setEmpno(int empno) {
  this.empno = empno;
 }
 public String getEname() {
  return ename;
 }
 public void setEname(String ename) {
  this.ename = ename;
 }
 public String getJob() {
  return job;
 }
 public void setJob(String job) {
  this.job = job;
 }
 public Date getHiredate() {
  return hiredate;
 }
 public void setHiredate(Date hiredate) {
  this.hiredate = hiredate;
 }
 public float getSal() {
  return sal;
 }
 public void setSal(float sal) {
  this.sal = sal;
 }
 
}

//IEmpDAO.java
package com.demo;

import java.util.List;

//IEmpDAO.java
//定義DAO操作標準
public interface IEmpDAO {
//doCreate主要執行資料庫的插入操作,操作時要傳入一個Emp物件
 public boolean doCreate(Emp emp)throws Exception;
  //emp增加的資料物件
  //return是否成功
 //findAll主要完成資料的查詢操作,因為是查詢的結果,所以使用List傳回
 public List findAll(String keyword)throws Exception;
  //keyword 查詢關鍵字
  //return傳回查詢結果,每一個Emp是一筆記錄
 //findById根據員工編號傳回一個Emp物件,其包含一個完整的資料資訊
 public Emp findById(int empno)throws Exception;
  //empno員工編號
  //return員工的VO物件
 /*
  doCreate()方法執行資料庫插入的操作,執行插入時要傳入一個Emp物件,此物件中有要資加的員工資訊
  findAll()主要完成資料的查詢,因為傳回的是多條查詢資訊,所以用List傳回,findById()主要是將Emp
    物件的編號傳回。
 */
}

//IEmpDAOImpl.java

package com.demo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class IEmpDAOImpl implements IEmpDAO{
 private Connection conn=null;
 private PreparedStatement pstmt=null;
 public IEmpDAOImpl(Connection conn){
  this.conn=conn;
 }
 public boolean doCreate(Emp emp) throws Exception {
  // TODO Auto-generated method stub
  boolean flag=false;
  String sql="INSERT INTO emp(empno, ename, job, hiredate, sal) VALUES (?,?,?,?,?)";
  this.pstmt=this.conn.prepareStatement(sql);
  this.pstmt.setInt(1,emp.getEmpno());
  this.pstmt.setString(2,emp.getEname());
  this.pstmt.setString(3,emp.getJob());
  this.pstmt.setDate(4,new java.sql.Date(emp.getHiredate().getTime()));
  this.pstmt.setFloat(5,emp.getSal());
  if(this.pstmt.executeUpdate() > 0){
   flag=true;
  }
  this.pstmt.close();
  return flag;
 }

 public List findAll(String keyword) throws Exception {
  // TODO Auto-generated method stub
  //定義和接收全部的資料
  Listall=new ArrayList();
  String sql="SELECT empno, ename, job, hiredate, sal FROM emp WHERE ename LIKE ? or job LIKE ?";
  this.pstmt=this.conn.prepareStatement(sql);
  this.pstmt.setString(1,"%"+keyword+"%");
  this.pstmt.setString(2,"%"+keyword+"%");
  ResultSet rs=this.pstmt.executeQuery();
  Emp emp=null;
  while(rs.next()){
   emp=new Emp();
   emp.setEmpno(rs.getInt(1));
   emp.setEname(rs.getString(2));
   emp.setJob(rs.getString(3));
   emp.setHiredate(rs.getDate(4));
   emp.setSal(rs.getFloat(5));
   all.add(emp);//向集合中增加物件
  }
  this.pstmt.close();
  return all;//傳回所有集合的結果
 }

 public Emp findById(int empno) throws Exception {
  // TODO Auto-generated method stub
  Emp emp=null;
  String sql="SELECT empno, ename, job, hiredate, sal FROM emp WHERE empno=?";
  this.pstmt=this.conn.prepareStatement(sql);
  this.pstmt.setInt(1,empno);
  ResultSet rs=this.pstmt.executeQuery();
  if(rs.next()){
   emp=new Emp();
   emp.setEmpno(rs.getInt(1));
   emp.setEname(rs.getString(2));
   emp.setJob(rs.getString(3));
   emp.setHiredate(rs.getDate(4));
   emp.setSal(rs.getFloat(5));
  }
  this.pstmt.close();
  return emp;//如果查詢不到結果則傳回null,預設為null
 }
 
}

//EmpDAOProxy.java

package com.demo;

import java.util.List;

public class EmpDAOProxy implements IEmpDAO{
 private DatabaseConnection dbc=null;
 private IEmpDAO dao=null;
 public EmpDAOProxy()throws Exception{
  this.dbc=new DatabaseConnection();
  this.dao=new IEmpDAOImpl(this.dbc.getConn());
 }
 public boolean doCreate(Emp emp) throws Exception {
  // TODO Auto-generated method stub
  boolean flag=false;
  try{
   if(this.dao.findById(emp.getEmpno())==null){
    flag=this.dao.doCreate(emp);
   }
  }catch(Exception e){
   throw e;
  }
  finally{
   this.dbc.close();
  }
  return flag;
 }

 public List findAll(String keyword) throws Exception {
  // TODO Auto-generated method stub
  List all=null;
  try{
   all=this.dao.findAll(keyword);
  }catch(Exception e){
   throw e;
  }
  finally{
   this.dbc.close();
  }
  return all;
 }

 public Emp findById(int empno) throws Exception {
  // TODO Auto-generated method stub
  Emp emp=null;
  try{
   emp=this.dao.findById(empno);
  }catch(Exception e){
   throw e;
  }finally{
   this.dbc.close();
  }
  return emp;
 }

}

//DatabaseConnection.java

package com.demo.dbc;

import java.sql.Connection;

public interface DatabaseConnection {
 public Connection getConnection();
 public void close(); 
}

//MySQLDatabaseConnection.java

package com.demo.dbc;

import java.sql.Connection;

public class MySQLDatabaseConnection implements DatabaseConnection {

 public void close() {
  // TODO Auto-generated method stub
  
 }

 public Connection getConnection() {
  // TODO Auto-generated method stub
  return null;
 }
 
}

執行結果:
首頁
註冊

執行emp_list.jsp
到資料庫查看