spring+struts+hibernate分页 完整版

spring+struts+hibernate分页运行原理分析如下:

1)当调用分页功能时:就会触发 SplitPageAction 类
2)SplitPageAction 类进而通过 PaginateService 类,把访问数据请求经spring,再传hibernate来访问数据库,提取数据。
3)最终将结果通过JSP页面来显示给用户。

package com.crb2b.util;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppContext {   //定义一个工具类,为了方便访问spring配置文件里面的bean。

     private static AppContext instance;
     private AbstractApplicationContext appContext;
   
     public synchronized static AppContext getInstance() {
      if (instance == null) {
        instance = new AppContext();
      }
      return instance;
    }

    private AppContext() {
      this.appContext = new ClassPathXmlApplicationContext(
          "applicationContext.xml");
    }

    public AbstractApplicationContext getAppContext() {
      return appContext;
    }

public static void main(String[] args) {
   // TODO Auto-generated method stub

}

}

package com.crb2b.util;

public class PageBean {                   //分页中用到的基本信息类PageBean

private int count = 0; // 记录总数

    private int pageSize = 20; // 每页显示记录数

    private int pageCount = 0; // 总页数

    private int page = 1; // 当前页数

    private String totalCountSQL;// 得到总记录数sql语句

    private String listSQL;// 得到查询记录sql语句

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        if (pageSize != 0) {
            pageCount = count / pageSize;
            if (count % pageSize != 0) {
                pageCount++;
            }
        }
        this.count = count;
    }

    public String getListSQL() {
        return listSQL;
    }

    public void setListSQL(String listSQL) {
        this.listSQL = listSQL;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public String getTotalCountSQL() {
        return totalCountSQL;
    }

    public void setTotalCountSQL(String totalCountSQL) {
        this.totalCountSQL = totalCountSQL;
    }

}

package com.crb2b.data.dao;

import java.io.Serializable;
import java.util.List;

import com.crb2b.util.PageBean;

public interface IPaginateDAO extends Serializable {    //定义IPaginateDAO接口。为hibernate访问数据库来用
public List getList(PageBean page);

    public String getToolsMenu(PageBean page);

    public Long getTotalCount(PageBean p, String str[], Object ob2[])
            throws Exception;

    public Long getTotalCount(PageBean page) throws Exception;

    public List getList(PageBean page, String str[], Object ob2[])
            throws Exception; 

 public List getListcommList(PageBean page) throws Exception ;
    public List getRentcommList(PageBean page) throws Exception ; 
   
  
 
}

package com.crb2b.data.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.crb2b.data.dao.IPaginateDAO;
import com.crb2b.util.PageBean;

public class PaginateDAO extends HibernateDaoSupport implements IPaginateDAO { //实现接口类,具体实现分页功能,及分页导航信息等。
   public String getToolsMenu(PageBean p) { 
       StringBuffer str = new StringBuffer(""); 
       int next, prev; 
       prev = p.getPage() - 1; 
       next = p.getPage() + 1; 
      
       if (p.getPage() > 1) { 
        str 
          .append("<a href=\"#\" onclick=\"document.forms(0).jumpPage.value=1;document.forms(0).submit(); \">首页</a> "); 
       } else { 
           //str.append("<a href=\"#\">首页</a> ");
           str.append("首页 ");
       } 
       if (p.getPage() > 1) { 
        str.append("<a href=\"#\" onclick='document.forms(0).jumpPage.value=" 
          + prev + ";document.forms(0).submit();'>上页</a> "); 
       } else { 
           //str.append("<a href=\"#\">上页</a> "); 
           str.append("上页 "); 
       } 
       if (p.getPage() < p.getPageCount()) { 
        str.append("<a href=\"#\" onclick='document.forms(0).jumpPage.value=" 
          + next + ";document.forms(0).submit();'>下页</a> "); 
       } else { 
         //str.append("<a href=\"#\" >下页</a> "); 
           str.append("下页 ");
       } 
       if (p.getPageCount() > 1 && p.getPage() != p.getPageCount()) { 
        str.append("<a href=\"#\" onclick='document.forms(0).jumpPage.value=" 
          + p.getPageCount() 
          + ";document.forms(0).submit();'>末页</a> "); 
       } else { 
        //str.append("<a href=\"#\" >末页</a> ");
          str.append("末页 ");
       } 
       str.append(" 共" + p.getCount() + "条记录"); 
       str 
         .append(" 每页<SELECT size=1 name=pagesize onchange='this.form.jumpPage.value=1;this.form.pageSize.value=this.value;this.form.submit();'>"); 
      
       if (p.getPageSize() == 3) { 
        str.append("<OPTION value=3 selected>3</OPTION>"); 
       } else { 
        str.append("<OPTION value=3>3</OPTION>"); 
       } 
      
       if (p.getPageSize() == 10) { 
        str.append("<OPTION value=10 selected>10</OPTION>"); 
       } else { 
        str.append("<OPTION value=10>10</OPTION>"); 
       } 
       if (p.getPageSize() == 20) { 
        str.append("<OPTION value=20 selected>20</OPTION>"); 
       } else { 
        str.append("<OPTION value=20>20</OPTION>"); 
       } 
       if (p.getPageSize() == 50) { 
        str.append("<OPTION value=50 selected>50</OPTION>"); 
       } else { 
        str.append("<OPTION value=50>50</OPTION>"); 
       } 
       if (p.getPageSize() == 100) { 
        str.append("<OPTION value=100 selected>100</OPTION>"); 
       } else { 
        str.append("<OPTION value=100>100</OPTION>"); 
       } 
       str.append("</SELECT>"); 
       str.append("条 分" + p.getPageCount() + "页显示 转到"); 
       str 
         .append("<SELECT size=1 name=Pagelist onchange='this.form.jumpPage.value=this.value;this.form.submit();'>"); 
       for (int i = 1; i < p.getPageCount() + 1; i++) { 
        if (i == p.getPage()) { 
         str.append("<OPTION value=" + i + " selected>" + i 
           + "</OPTION>"); 
        } else { 
         str.append("<OPTION value=" + i + ">" + i + "</OPTION>"); 
        } 
       } 
       str.append("</SELECT>页"); 
       str.append("<INPUT type=hidden value=" + p.getPage() 
         + " name=\"pages\" > "); 
       str.append("<INPUT type=hidden value=" + p.getPageSize() 
         + " name=\"pageSize\"> "); 
       return str.toString(); 
      } 
      
      /**
       * 获取总条数
       */
      public Long getTotalCount(PageBean p) throws Exception {
       List list = getHibernateTemplate().find(p.getTotalCountSQL()); 
       long count = 0; 
       if (list.size() > 0) { 
        count = new Long(""+list.get(0)); 
       } 
       return count; 
      } 
    
    
      /**
       * 获取总条数   带有参数的
       */
      public Long getTotalCount(PageBean p, String str[], Object ob2[])throws Exception {
          List list=new ArrayList();
          if(str!=null && str.length>0){
              list = getHibernateTemplate().findByNamedParam(p.getTotalCountSQL(), str, ob2);
          }else{
              list=this.getHibernateTemplate().find(p.getTotalCountSQL());
          }
          long count = 0; 
          if (list.size() > 0) {        
            count = new Long(""+list.get(0)); 
           } 
           return count; 
     }
     
      /**
       * 查询信息进行分页
       */
      public List getList(final PageBean p) {
           return this.getHibernateTemplate().executeFind(new HibernateCallback(){
              public Object doInHibernate(Session session){
                  Query q = session.createQuery(p.getListSQL());
                   q.setFirstResult((p.getPage() - 1) * p.getPageSize()); 
                   q.setMaxResults(p.getPageSize()); 
                        return q.list();
             }
         });
      } 
     
      /**
       * 查询信息进行分页 带有参数的
       */
      public List getList(final PageBean p,final String str[], final Object ob2[]) { 
          return this.getHibernateTemplate().executeFind(new HibernateCallback(){
              public Object doInHibernate(Session session){
                  Query q = session.createQuery(p.getListSQL());
                  if(str!=null){
                       for (int i = 0; i < str.length; i++) { 
                        q.setParameter(str[i], ob2[i]); 
                       } 
                  }
                  q.setFirstResult((p.getPage() - 1) * p.getPageSize()); 
                  q.setMaxResults(p.getPageSize()); 
                  return q.list();
             }
         });   
      } 
    
    
         //splitListCommonPage
   public List getListcommList(final PageBean page) throws Exception {  //此方法为用原生sql访问数据库所用
  
    return (List) this.getHibernateTemplate().executeFind(new HibernateCallback() {
     public Object doInHibernate(Session session)throws HibernateException {   
      //Query q =session.createSQLQuery(sql.toString()).addEntity("LICO",ListCommon.class);
    
      Query q=session.createSQLQuery(page.getListSQL()).addScalar("LICOID",Hibernate.INTEGER).addScalar("LISTID",Hibernate.STRING).
      addScalar("LISTSTATUS",Hibernate.STRING).addScalar("LISTSTREET",Hibernate.STRING).addScalar("LISTCOUNTY",Hibernate.STRING).addScalar("LISTBEDROOM",Hibernate.STRING).
      addScalar("LISTDRAWINGROOM",Hibernate.INTEGER).addScalar("LISTTOILET",Hibernate.INTEGER).addScalar("LISTFLOOR",Hibernate.INTEGER).addScalar("LISTTOTALFLOOR",Hibernate.INTEGER).
      addScalar("LISTBUILDAREA",Hibernate.FLOAT).addScalar("LISTPRICE",Hibernate.DOUBLE).addScalar("LISTTOTALPRICE",Hibernate.DOUBLE).addScalar("LISTDOOR",Hibernate.STRING).addScalar("LISTMEMBERMID",Hibernate.STRING) ;
    
      q.setFirstResult((page.getPage() - 1) * page.getPageSize()); 
                   q.setMaxResults(page.getPageSize()); 
      return q.list();
     }  
    });
   }

   public List getRentcommList(final PageBean page) throws Exception {    //此方法为用原生sql访问数据库所用

    return (List) this.getHibernateTemplate().executeFind(new HibernateCallback() {
     public Object doInHibernate(Session session)throws HibernateException {   
      //Query q =session.createSQLQuery(sql.toString()).addEntity("LICO",ListCommon.class);
    
      Query q=session.createSQLQuery(page.getListSQL()).addScalar("RECOID",Hibernate.INTEGER).addScalar("RENTID",Hibernate.STRING).
      addScalar("RENTSTATUS",Hibernate.STRING).addScalar("RENTSTREET",Hibernate.STRING).addScalar("RENTCOUNTY",Hibernate.STRING).
      addScalar("RENTBEDROOM",Hibernate.INTEGER).addScalar("RENTDRAWINGROOM",Hibernate.INTEGER).
      addScalar("RENTTOILET",Hibernate.INTEGER).addScalar("RENTFLOOR",Hibernate.INTEGER).addScalar("RENTTOTALFLOOR",Hibernate.INTEGER).
      addScalar("RENTBUILDAREA",Hibernate.FLOAT).addScalar("RENTRENT",Hibernate.STRING).addScalar("RENTDOOR",Hibernate.STRING) ;
 
      q.setFirstResult((page.getPage() - 1) * page.getPageSize()); 
                   q.setMaxResults(page.getPageSize()); 
      return q.list();
     }  
    });
   }
    
   
}

package com.crb2b.model.service;

import java.io.Serializable;
import java.util.List;

import com.crb2b.util.PageBean;

public interface IPaginateService extends Serializable {    //为hibernate 和spring 关联一起工作,而定义的接口
public List getList(PageBean page);

    public String getToolsMenu(PageBean page);

    public Long getTotalCount(PageBean p, String str[], Object ob2[])
            throws Exception;

    public Long getTotalCount(PageBean page) throws Exception;

    public List getList(PageBean page, String str[], Object ob2[])
            throws Exception;
  
    public List getListcommList(PageBean page) throws Exception ;
    public List getRentcommList(PageBean page) throws Exception ;
 

}

package com.crb2b.model.service.impl;

import java.util.List;

import com.crb2b.data.dao.IPaginateDAO;
import com.crb2b.model.service.IPaginateService;
import com.crb2b.util.PageBean;

public class PaginateService implements IPaginateService {   //实现 为hibernate 和spring 关联一起工作,而定义的接口 类

private IPaginateDAO paginateDAO;

public IPaginateDAO getPaginateDAO() {
   return paginateDAO;
}

public void setPaginateDAO(IPaginateDAO paginateDAO) {
   this.paginateDAO = paginateDAO;
}

public List getList(PageBean page) {
   return this.getPaginateDAO().getList(page);
}

    public String getToolsMenu(PageBean page){
   return this.getPaginateDAO().getToolsMenu(page);
}

    public Long getTotalCount(PageBean p, String str[], Object ob2[])
            throws Exception{
           return this.getPaginateDAO().getTotalCount(p, str, ob2);
        }

    public Long getTotalCount(PageBean page) throws Exception{
   return this.getPaginateDAO().getTotalCount(page);
}

    public List getList(PageBean page, String str[], Object ob2[])
            throws Exception{
           return this.getPaginateDAO().getList(page, str, ob2);
        }

public List getListcommList(PageBean page) throws Exception {
   // TODO Auto-generated method stub
   return this.getPaginateDAO().getListcommList(page);
}

public List getRentcommList(PageBean page) throws Exception {
   // TODO Auto-generated method stub
   return this.getPaginateDAO().getRentcommList(page);
}
  
}

ApplicationContext.xml 中添加以下内容:   //spring 配置文件,将hibernate 和spring 关联一起工作
........................................
<bean id="paginateDAO" class="com.crb2b.data.dao.impl.PaginateDAO">
    <property name="sessionFactory">
      <ref local="sessionFactory"/>
    </property>
    </bean>
  
    <bean id="paginateService"
   class="com.crb2b.model.service.impl.PaginateService">
   <property name="paginateDAO">
   <ref local="paginateDAO"/>
   </property>
</bean>

..........................

package com.crb2b.struts.action;            
import org.apache.struts.action.Action;
import com.crb2b.util.AppContext;
import com.crb2b.model.service.IPaginateService;

public class BaseAction extends Action {     //定义一个基类,

public BaseAction() {
   super();
}

protected IPaginateService getPaginateService(){  // 发布一个方法,让请求分页功能类直接调用,进行数据提取。
   return (IPaginateService)AppContext.getInstance().getAppContext().getBean("paginateService");
}
}

/**
* 分页代码示例 调用
* Copyright @ 2008 NANJING YIZHOU SOFTWARE Co. Ltd.
* All right reserved.
*
* @author xuxinlong
*
*/
public class SplitPageAction extends BaseAction {   //分页请求类,

     private PaginateInterface pageinate;
     public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
       
         HttpSession session=request.getSession();
         Object obj=session.getAttribute("KDUser");
         if(obj!=null){
             PageBean pb=new PageBean();
             String jumpPage=request.getParameter("jumpPage");   
             String pageSize=request.getParameter("pageSize");
             if(jumpPage!=null && !"".equals(jumpPage) && pageSize!=null && !"".equals(pageSize)){   
                 pb.setPageSize(new Integer(pageSize));
             }else{
                 jumpPage="1";
             }
             String strSqlCnt="select count(*) from TUsertable";
             String strSqlInfo="select u from TUsertable u";
           
             pb.setTotalCountSQL(strSqlCnt);
             pb.setListSQL(strSqlInfo);
             pb.setPage(new Integer(jumpPage));
           
             pb.setCount(this.getPaginateService().getTotalCount(pb).intValue());
             List listUser=this.getPaginateService().getList(pb);
             request.setAttribute("info", this.getPaginateService().getToolsMenu(pb));
             request.setAttribute("listUser", listUser);
           
         return mapping.findForward("pagelist");
         }
       
       
         return mapping.findForward("error");
     }
     public PaginateInterface getPageinate() {
         return pageinate;
     }
     public void setPageinate(PaginateInterface pageinate) {
         this.pageinate = pageinate;
     }
   

}

JSP中使用

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>

<html>
<head>


     <title>分页演示</title>
   
     <link href="css/list.css" rel="stylesheet" type="text/css" />
<link href="css/table.css" rel="stylesheet" type="text/css" />

</head>
 
<body> <center><font size="5">分页演示</font></center>
<form action="splitPage.do" method="post" name="splitPageForm">       //表单提交,交给请求分页类。
<input type="hidden" name="jumpPage">
<table width="96%" class="center" border="0" cellpadding="0" cellspacing="0">
<tr class="table_tr">
<td >

<table class="yizhou_table" ">
   <tr class="table_tr"   >
     <th class="table_c_01">用户ID</th>
     <th class="table_c_01">用户名</th>
     <th class="table_c_01">姓名</th>
     <th class="table_c_01">邮箱</th>   
     <th class="table_c_01">性别</th>
     <th class="table_c_01">年龄</th>
     <th class="table_c_01">手机</th>
   </tr>
<logic:notEmpty name="listUser">
<logic:iterate id="detial" name="listUser">
   <tr>   
[color=darkred]     <td   height="20"> ${detial.userid}</td>  
     <td> ${detial.username}</td>    //标签显示 ,这里显示的内容,可能跟截图字段不一样,可自已设定
     <td> ${detial.uname}</td>
     <td> ${detial.email}</td>
     <td> ${detial.sex}</td>
     <td> ${detial.age}</td>
     <td> ${detial.mtel}</td>

   </tr>[/color]
</logic:iterate>
</logic:notEmpty>
<tr>


   <td colspan="7" align="right" align="left" class="table_c_02" height=28 >
     ${info}            // 用来显示: (首页 上页 下页 。。。)导航信息。
</td>
</tr>
</table>

</td></tr></table>
</form>
</body>
</html>

你可能感兴趣的:(DAO,spring,sql,Hibernate,struts)