DAO设计模式&&struts分页

 今天在网上看了dao设计模式和一个struts分页方法,自己将他们结合起来写了一个程序实例以加深对他们的理解和运用。

程序实例如下:

首先用mysql创建一个person表,sql语句为:
create   table  person
(
pid 
int  auto_increment,
pname 
varchar ( 20 ),
primary   key  (pid)
);

insert   into  person(pname)  values ( ' x ' );
insert   into  person(pname)  values ( ' y ' );
insert   into  person(pname)  values ( ' z ' );
insert   into  person(pname)  values ( ' a ' );
insert   into  person(pname)  values ( ' b ' );
insert   into  person(pname)  values ( ' c ' );
insert   into  person(pname)  values ( ' d ' );
insert   into  person(pname)  values ( ' e ' );
insert   into  person(pname)  values ( ' f ' );
insert   into  person(pname)  values ( ' g ' );
insert   into  person(pname)  values ( ' h ' );
insert   into  person(pname)  values ( ' k ' );
insert   into  person(pname)  values ( ' j ' );
insert   into  person(pname)  values ( ' l ' );

dao工厂类DAOFactory.java如下:
/ Abstract  class  DAO Factory
public   abstract   class  DAOFactory  {

  
// List of DAO types supported by the factory
  public static final int MYSQL=1;
  
//...

  
// There will be a method for each DAO that can be 
  
// created. The concrete factories will have to 
  
// implement these methods.
  public abstract PersonDAO getPersonDAO();
  
// ...

  
public static DAOFactory getDAOFactory(
      
int whichFactory) {
  
    
switch (whichFactory) {
      
case MYSQL: 
          
return new MysqlDAOFactory();
      
//...
      default
          
return null;
    }

  }

}

MysqlDAOFactory.java代码如下:
import  java.sql.Connection;
import  java.sql.DriverManager;
import  java.sql.ResultSet;
import  java.sql.Statement;

public   class  MysqlDAOFactory  extends  DAOFactory {
     
private static final String DRIVER=
        
"com.mysql.jdbc.Driver";
      
private static final String DBURL=
        
"jdbc:mysql://localhost/daotest?user=root&password=101213&useUnicode=true&characterEncoding=gb2312";

      
// method to create Cloudscape connections
      public static Connection createConnection() {
        
// Use DRIVER and DBURL to create a connection
        
// Recommend connection pool implementation/usage
          Connection conn=null;
          
try{
              Class.forName(DRIVER).newInstance();
              conn
= DriverManager.getConnection(DBURL);
          }
catch(Exception e){
              e.printStackTrace();
          }

          
return conn;
      }

      
      
public static void closeAll(Connection conn, Statement stmt, ResultSet rs) {
            
if (rs != null{
                
try {
                    rs.close();
                }
 catch (Exception e) {
                    System.out.println(
"close resultset failed." + e.getMessage());
                }

            }

            
if (stmt != null{
                
try {
                    stmt.close();
                }
 catch (Exception e) {
                    System.out.println(
"close statement failed." + e.getMessage());
                }

            }

            
if (conn != null{
                
try {
                    conn.close();
                }
 catch (Exception e) {
                    System.out.println(
"close connection failed." +  e.getMessage());
                }

            }

        }

      
      
public PersonDAO getPersonDAO() {
        
// CloudscapeCustomerDAO implements CustomerDAO
        return new MysqlPersonDAO();
      }


}


dao接口PersonDAO.java如下:
import  java.util.Collection;

import  javax.sql.RowSet;

public   interface  PersonDAO  {
      
public int insertPerson(String pname);
      
public boolean deletePerson(int pid);
      
public Person findPerson(int pid);
      
public boolean updatePerson(Person p);
      
//public RowSet selectCustomersRS();
      public Collection selectCustomersTO(String sql,int startIndex,int recordPerPage);
      
//...
    }

执行此接口的MysqlPersonDAO.java如下:
/ CloudscapeCustomerDAO implementation of the 
// CustomerDAO interface. This class can contain all
// Cloudscape specific code and SQL statements. 
// The client is thus shielded from knowing 
// these implementation details.

// import java.sql.*;
import  java.sql.Connection;
import  java.sql.ResultSet;
import  java.sql.SQLException;
import  java.sql.Statement;
import  java.util.ArrayList;
import  java.util.Collection;

// import javax.sql.RowSet;

public   class  MysqlPersonDAO  implements  
 PersonDAO 
{
    
    
private int totalPerson=0;

   
public int getTotalPerson() {
        
return totalPerson;
    }


    
public void setTotalPerson(int totalPerson) {
        
this.totalPerson = totalPerson;
    }


public MysqlPersonDAO() {
 
// initialization 
       }


// The following methods can use
// CloudscapeDAOFactory.createConnection() 
// to get a connection as required

public int insertPerson(String pname) {
 
// Implement insert customer here.
 
// Return newly created customer number
 
// or a -1 on error
    return 0;
}


public boolean deletePerson(int pid) {
 
// Implement delete customer here
 
// Return true on success, false on failure
    return false;
}


public Person findPerson(int pid) {
 
// Implement find a customer here using supplied
 
// argument values as search criteria
 
// Return a Transfer Object if found,
 
// return null on error or if not found
    return null;
}


public boolean updatePerson(Person p) {
 
// implement update record here using data
 
// from the customerData Transfer Object
 
// Return true on success, false on failure or
 
// error
    return false;
}


//public RowSet selectCustomersRS() {
 
// implement search customers here using the
 
// supplied criteria.
 
// Return a RowSet. 
    
//return null;
//}

 
public Collection selectCustomersTO(String sql,int startIndex,int recordPerPage) {
 
// implement search customers here using the
 
// supplied criteria.
 
// Alternatively, implement to return a Collection 
 
// of Transfer Objects.
     ArrayList pList=new ArrayList();
     Connection conn
=null;
     Statement stmt
=null;
     ResultSet rs
=null;
     
try{
         conn
=MysqlDAOFactory.createConnection();
         stmt
=conn.createStatement();
         rs
=stmt.executeQuery(sql);
         rs.last();
         totalPerson
=rs.getRow();
         rs.absolute(startIndex);
//将指针移动到此 ResultSet 对象的给定行编号
         for(int i=0;i<recordPerPage;i++){
             Person p
=new Person();
             p.setPid(rs.getInt(
"pid"));
             p.setPname(rs.getString(
"pname"));
             pList.add(p);
             rs.next();
         }

     }
catch(SQLException e){
         e.printStackTrace();
     }
finally{
         MysqlDAOFactory.closeAll(conn, stmt, rs);
     }

    
return pList;
  }

//...
}


与数据库表对应的Person.java类如下:
public   class  Person  implements  java.io.Serializable {
    
private int pid;
    
private String pname;
    
    
public Person(){
        
    }

    
    
public Person(int pid,String pname){
        
this.pid=pid;
        
this.pname=pname;
    }


    
public int getPid() {
        
return pid;
    }


    
public void setPid(int pid) {
        
this.pid = pid;
    }


    
public String getPname() {
        
return pname;
    }


    
public void setPname(String pname) {
        
this.pname = pname;
    }

    
    

}

分页处理类PageInfo.java如下:
/ 用于记录分页的记录
import  java.io.Serializable;

public   class  PageInfo  implements  Serializable  {

    
private int recordCountNumber = 0// 总记录数

    
private int pageCountNumber = 0// 总页数

    
private int recordPerPage = 0// 每页记录数

    
private int currentPage = 0// 当前页数

    
private int previousPageNumber = 0// 当前页的前一页数

    
private int nextPageNumber = 0// 当前页的后一页数

    
public PageInfo() {
    }

    
    
public int getRecordCountNumber() {
        
return this.recordCountNumber;
    }


    
public int getPageCountNumber() {
        
if (recordCountNumber == 0)
            
return 0;
        
if (recordPerPage == 0)
            
return 1;
        
if (this.recordCountNumber % this.recordPerPage == 0{
            
this.pageCountNumber = this.recordCountNumber / this.recordPerPage;
        }
 else {
            
this.pageCountNumber = (this.recordCountNumber / this.recordPerPage) + 1;
        }

        
return this.pageCountNumber;
    }


    
public int getRecordPerPage() {
        
return this.recordPerPage;
    }

    
public void setRecordPerPage(int recordPerPage){
        
this.recordPerPage=recordPerPage;
    }


    
public int getCurrentPage() {
        
return this.currentPage;
    }


    
public int getLastPageNumber() {
        
return this.pageCountNumber;
    }


    
public int getPreviousPageNumber() {
        
this.previousPageNumber = this.currentPage - 1;
        
return this.previousPageNumber;
    }


    
public int getNextPageNumber() {
        
this.nextPageNumber = this.currentPage + 1;
        
return this.nextPageNumber;
    }


    
public void setCurrentPage(int currentPage) {
        
this.currentPage = currentPage;
    }


    
public void setRecordCountNumber(int recordCountNumber) {
        
this.recordCountNumber = recordCountNumber;
    }

    
}


getPerson.jsp代码如下:
<% @ page language="java" pageEncoding="GB18030" %>

<% @ taglib uri="/WEB-INF/struts-html.tld" prefix="html"  %>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
< html:html >
  
< head >
    
    
< title > getPerson.jsp </ title >

    
< meta  http-equiv ="pragma"  content ="no-cache" >
    
< meta  http-equiv ="cache-control"  content ="no-cache" >

  
</ head >
  
  
< body >
    
< form  action ="getPerson.do?method=showFirst"  method ="post" >
    
< html:submit > 得到人员信息 </ html:submit >
    
</ form >
  
</ body >
</ html:html >

响应jsp的GetPersonAction.java继承DispatchAction,写了五个方法(showFirst,showPrivious,showNext,showLast,showRandom),分别显示第一页,上一页,下一页,最后一页和任意一页,其实只需要showRandom一个方法就可以了,不过它要从jsp页面得到一个参数,即要显示的是第几页。而前四个方法不需要。具体代码如下:
import  java.util.Collection;

import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;
import  javax.servlet.http.HttpSession;

import  org.apache.struts.action.ActionForm;
import  org.apache.struts.action.ActionForward;
import  org.apache.struts.action.ActionMapping;
import  org.apache.struts.actions.DispatchAction;

import  dao.DAOFactory;
import  dao.MysqlPersonDAO;
import  dao.PageInfo;
import  dao.PersonDAO;

/** 
 * MyEclipse Struts
 * Creation date: 07-28-2007
 * 
 * XDoclet definition:
 * @struts.action input="/getPerson.jsp" validate="true"
 
*/

public   class  GetPersonAction  extends  DispatchAction  {
    
/*
     * Generated Methods
     
*/


    
    
public ActionForward showFirst(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
{
        
// TODO Auto-generated method stub
        DAOFactory mysqlFactory =   
              DAOFactory.getDAOFactory(DAOFactory.MYSQL);
        PersonDAO pDAO 
= 
              mysqlFactory.getPersonDAO();
        String sql
="select * from person";
        HttpSession session
=request.getSession();
        PageInfo pInfo
=(PageInfo)session.getAttribute("pageinfo");
        
if(pInfo==null){
        pInfo
=new PageInfo();
        pInfo.setRecordPerPage(
10);
        }

        Collection pList
=pDAO.selectCustomersTO(sql, 1, pInfo.getRecordPerPage());
        pInfo.setRecordCountNumber(((MysqlPersonDAO)pDAO).getTotalPerson());
        pInfo.setCurrentPage(
1);
        session.setAttribute(
"pageinfo", pInfo);
        request.setAttribute(
"plist", pList);
        
        
return mapping.findForward("personInfo");
    }

    
    
public ActionForward showPrivious(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
{
        
// TODO Auto-generated method stub
        DAOFactory mysqlFactory =   
              DAOFactory.getDAOFactory(DAOFactory.MYSQL);
        PersonDAO pDAO 
= 
              mysqlFactory.getPersonDAO();
        String sql
="select * from person";
        HttpSession session
=request.getSession();
        PageInfo pInfo
=(PageInfo)session.getAttribute("pageinfo");
        Collection pList
=pDAO.selectCustomersTO(sql, (pInfo.getPreviousPageNumber()-1*
                pInfo.getRecordPerPage()
+1, pInfo.getRecordPerPage());
        pInfo.setRecordCountNumber(((MysqlPersonDAO)pDAO).getTotalPerson());
        pInfo.setCurrentPage(pInfo.getPreviousPageNumber());
        session.setAttribute(
"pageinfo", pInfo);
        request.setAttribute(
"plist", pList);
        
        
return mapping.findForward("personInfo");
    }

    
    
public ActionForward showNext(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
{
        
// TODO Auto-generated method stub
        DAOFactory mysqlFactory =   
              DAOFactory.getDAOFactory(DAOFactory.MYSQL);
        PersonDAO pDAO 
= 
              mysqlFactory.getPersonDAO();
        String sql
="select * from person";
        HttpSession session
=request.getSession();
        PageInfo pInfo
=(PageInfo)session.getAttribute("pageinfo");
        Collection pList
=pDAO.selectCustomersTO(sql, pInfo.getCurrentPage()*pInfo.getRecordPerPage(), pInfo.getRecordPerPage());
        pInfo.setRecordCountNumber(((MysqlPersonDAO)pDAO).getTotalPerson());
        pInfo.setCurrentPage(pInfo.getNextPageNumber());
        session.setAttribute(
"pageinfo", pInfo);
        request.setAttribute(
"plist", pList);
        
        
return mapping.findForward("personInfo");
    }

    
    
public ActionForward showLast(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
{
        
// TODO Auto-generated method stub
        DAOFactory mysqlFactory =   
              DAOFactory.getDAOFactory(DAOFactory.MYSQL);
        PersonDAO pDAO 
= 
              mysqlFactory.getPersonDAO();
        String sql
="select * from person";
        HttpSession session
=request.getSession();
        PageInfo pInfo
=(PageInfo)session.getAttribute("pageinfo");
        Collection pList
=pDAO.selectCustomersTO(sql, (pInfo.getPageCountNumber()-1*
                pInfo.getRecordPerPage()
+1, pInfo.getRecordPerPage());
        pInfo.setRecordCountNumber(((MysqlPersonDAO)pDAO).getTotalPerson());
        pInfo.setCurrentPage(pInfo.getLastPageNumber());
        session.setAttribute(
"pageinfo", pInfo);
        request.setAttribute(
"plist", pList);
        
        
return mapping.findForward("personInfo");
    }

    
    
public ActionForward showRandom(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
{
        
// TODO Auto-generated method stub
        DAOFactory mysqlFactory =   
              DAOFactory.getDAOFactory(DAOFactory.MYSQL);
        PersonDAO pDAO 
= 
              mysqlFactory.getPersonDAO();
        String pageNumber
=request.getParameter("pageNumber");
        
int page=Integer.parseInt(pageNumber);
        String sql
="select * from person";
        HttpSession session
=request.getSession();
        PageInfo pInfo
=(PageInfo)session.getAttribute("pageinfo");
        Collection pList
=pDAO.selectCustomersTO(sql, (page-1*
                pInfo.getRecordPerPage()
+1, pInfo.getRecordPerPage());
        pInfo.setRecordCountNumber(((MysqlPersonDAO)pDAO).getTotalPerson());
        pInfo.setCurrentPage(page);
        session.setAttribute(
"pageinfo", pInfo);
        request.setAttribute(
"plist", pList);
        
        
return mapping.findForward("personInfo");
    }

    
    
}

显示数据信息页面personInfo.jsp如下:
<% @ page language="java" pageEncoding="GB18030" %>
<% @ page import="dao.PageInfo"  %>

<% @ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"  %>
<% @ taglib uri="/WEB-INF/struts-html.tld" prefix="html"  %>
<% @ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"  %>
<% @ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles"  %>

<%
  PageInfo pinfo
=(PageInfo)session.getAttribute("pageinfo");
  
int pageCount=pinfo.getPageCountNumber();
%>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
< html:html >
  
< head >
    
    
< title > personInfo.jsp </ title >

    
< meta  http-equiv ="pragma"  content ="no-cache" >
    
< meta  http-equiv ="cache-control"  content ="no-cache" >
    
< meta  http-equiv ="expires"  content ="0" >     
    
< meta  http-equiv ="keywords"  content ="keyword1,keyword2,keyword3" >
    
< meta  http-equiv ="description"  content ="This is my page" >
    
<!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    
-->
    
    
< script  type ="text/javascript" >
    
function pageSelected(){
    document.form1.pageNumber.selectedIndex
=<%=pinfo.getCurrentPage()-1 %>;
    }

    
function formSubmit(){
    document.form1.submit();
    }

    
</ script >

  
</ head >
  
  
< body  onLoad ="pageSelected()" >
  
    
< center >
    
< table >
    
< caption > 人员信息 </ caption >
    
< tr >
    
< td > 编号 </ td >
    
< td > 姓名 </ td >
    
</ tr >
    
< logic:present  name ="plist" >
    
< logic:iterate  id ="person"  name ="plist" >
    
< tr >
    
< td >
    
< bean:write  name ="person"  property ="pid" />
    
</ td >
    
< td >
    
< bean:write  name ="person"  property ="pname" />
    
</ td >
    
</ tr >
    
</ logic:iterate >
    
</ logic:present >
    
</ table >
    
< table >
    
< tr >
    
< td >
    共
< bean:write  name ="pageinfo"  property ="recordCountNumber"  scope ="session" /> 条记录
    
</ td >
    
< td >
    共
< bean:write  name ="pageinfo"  property ="pageCountNumber"  scope ="session" />
    
</ td >
    
< td >
    当前第
< bean:write  name ="pageinfo"  property ="currentPage"  scope ="session" />
    
</ td >
    
< td >
    
< html:link  href ="/DAOTest/getPerson.do?method=showFirst" >  首页  </ html:link >
    
</ td >
    
< td >
    
< logic:equal  name ="pageinfo"  property ="currentPage"  value ="1" >
    上一页
    
</ logic:equal >
    
< logic:notEqual  name ="pageinfo"  property ="currentPage"  value ="1" >
    
< html:link  href ="/DAOTest/getPerson.do?method=showPrivious" >
    上一页
    
</ html:link >
    
</ logic:notEqual >
    
</ td >
    
< td >
    
< logic:equal  name ="pageinfo"  property ="currentPage"  value ="<%=String.valueOf(pageCount) %>" >
    下一页
    
</ logic:equal >
    
< logic:notEqual  name ="pageinfo"  property ="currentPage"  value ="<%=String.valueOf(pageCount) %>" >
    
< html:link  href ="/DAOTest/getPerson.do?method=showNext" >
    下一页
    
</ html:link >
    
</ logic:notEqual >
    
</ td >
    
< td >
    
< html:link  href ="/DAOTest/getPerson.do?method=showLast" >  尾页 </ html:link >
    
</ td >
    
< td >
    
< form  action ="/DAOTest/getPerson.do?method=showRandom"  method ="post"  name ="form1" >
    
< select  name ="pageNumber"  onChange ="formSubmit()" >
    
<%
     
for(int i=1;i<=pageCount;i++){
     
%>
   
< option  value ="<%=i %>" >
   --第
<% = %> 页--
   
</ option >
    
<% %>
    
</ select >
    
</ form >
    
< td >
    
</ table >
    
</ center >
  
</ body >
</ html:html >

struts-config.xml如下:
<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd" >

< struts-config >
  
< data-sources  />
  
< form-beans  />
  
< global-exceptions  />
  
< global-forwards  />
  
< action-mappings  >
    
< action
      
input ="/getPerson.jsp"
      path
="/getPerson"
      parameter
="method"
      type
="com.iss.struts.action.GetPersonAction" >
      
< forward  name ="personInfo"  path ="/personInfo.jsp"   />
    
</ action >

  
</ action-mappings >

  
< message-resources  parameter ="com.iss.struts.ApplicationResources"   />
</ struts-config >

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值