`

收藏:struts spring hibernate实现数据库记分页显示

阅读更多
struts+spring+hibernate实现数据库记分页显示

要分页就必须要有取数据库的起始位置和取多少记录,还有要有总记录

用spring来结合hibernate实现分页,

首先创建一个PageBean.java:

package com.binghe.spring;

public class 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;
 }
}
第二,创建一个接口:PaginateInterface.java

package com.binghe.spring;

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

public interface PaginateInterface extends Serializable {
 public List getList(PageBean page);

 public String getToolsMenu(PageBean page);

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

 public int getTotalCount(PageBean page) throws Exception;

 public List getList(PageBean page, String str[], Object ob2[])
   throws Exception;
}
第三,创建一个继承spring 的org.springframework.orm.hibernate3.support.HibernateDaoSupport的类Paginate.java,原码如下

package com.binghe.spring;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class Paginate extends HibernateDaoSupport implements PaginateInterface {

 /**
  * 显示用的菜单
  */
 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).pages.value=1;document.forms(0).submit();\">首页</a>&nbsp;");
  } else {
   str.append("<a href=\"#\">首页</a>&nbsp;");
  }
  if (p.getPage() > 1) {
   str.append("<a href=\"#\" onclick='document.forms(0).pages.value="
     + prev + ";document.forms(0).submit();'>上页</a>&nbsp;");
  } else {
   str.append("<a href=\"#\">上页</a>&nbsp;");
  }
  if (p.getPage() < p.getPageCount()) {
   str.append("<a href=\"#\" onclick='document.forms(0).pages.value="
     + next + ";document.forms(0).submit();'>下页</a>&nbsp;");
  } else {
   str.append("<a href=\"#\" >下页</a>&nbsp;");
  }
  if (p.getPageCount() > 1 && p.getPage() != p.getPageCount()) {
   str.append("<a href=\"#\"  onclick='document.forms(0).pages.value="
     + p.getPageCount()
     + ";document.forms(0).submit();'>末页</a>&nbsp;&nbsp;");
  } else {
   str.append("<a href=\"#\" >末页</a>&nbsp;&nbsp;");
  }
  str.append(" 共" + p.getCount() + "条记录");
  str
    .append("  每页<SELECT size=1 name=pagesize onchange='this.form.pages.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.pages.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 int getTotalCount(PageBean p) throws Exception {

  List list = getHibernateTemplate().find(p.getTotalCountSQL());
  int count = 0;
  if (list.size() > 0) {
   count = ((Integer) list.get(0)).intValue();
  }
  return count;
 }

 public List getList(PageBean p) {
  Session session = this.getSession();
  Query q = session.createQuery(p.getListSQL());
  q.setFirstResult((p.getPage() - 1) * p.getPageSize());
  q.setMaxResults(p.getPageSize());
  return q.list();
 }

 public List getList(PageBean p, String str[], Object ob2[]) {
  Session session = this.getSession();
  Query q = session.createQuery(p.getListSQL());
  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();
 }

 public int getTotalCount(PageBean p, String str[], Object ob2[])
   throws Exception {

  List list = getHibernateTemplate().findByNamedParam(
    p.getTotalCountSQL(), str, ob2);
  int count = 0;
  if (list.size() > 0) {
   count = ((Integer) list.get(0)).intValue();
  }
  return count;
 }
}
这样就定义好了分页的准备工作,下面就是怎样使用了。在spring中配置好,上面的借口要注入的地方,这是在spring配置文件中目标代码的配置代码:

<bean id="paginateProxy"
  class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
  <property name="transactionManager">
   <ref bean="transactionManager" />
  </property>
  <property name="target">
   <ref local="paginate" />
  </property>
  <property name="transactionAttributes">
   <props>
    <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
   </props>
  </property>
 </bean>

注入的地方:在bookTypeDAO中要调用目标方法

<bean id="bookTypeDAO"
  class="com.binghe.spring.booktype.BookTypeDAOImp">
  <property name="sessionFactory">
   <ref local="sessionFactory" />
  </property>
  <property name="paginate">
   <ref bean="paginateProxy" />
  </property>
 </bean>

在action中得到页面传来的页数和页面显示的记录数:

public ActionForward displayAll(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  HttpSession session = request.getSession();
  ActionMessages errors = new ActionMessages();
  UserBean ub = new UserBean();
  if (session.getAttribute(Constants.SESSION_USER) != null) {
   ub = (UserBean) session.getAttribute(Constants.SESSION_USER);
  } else {
   errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
     "system.logon.not.logon"));
   saveMessages(request, errors);
   return mapping.findForward(Constants.FORWARD_LOGON);
  }
  PageBean page = new PageBean();
  String pagesize = request.getParameter("pagesize");
  String pages = request.getParameter("pages");
  if (pagesize != null) {
   page.setPageSize(Integer.parseInt(pagesize));
  }
  if (pages != null) {
   page.setPage(Integer.parseInt(pages));
  }
  try {
   List bts = bookTypeDAO.findAllBookType(page);
   request.setAttribute(Constants.KEY_BOOKTYPES, bts);
  } catch (Exception e) {
   e.printStackTrace();
  }
  request.setAttribute("toolsmenu", bookTypeDAO.getPaginate()
    .getToolsMenu(bookTypeDAO.getPageBean()));
  return mapping.findForward(Constants.FORWARD_SUCCESS);
 }

下面是BookDAO接口代码:

package com.binghe.spring.booktype;

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

import com.binghe.hibernate.booktype.BookType;
import com.binghe.spring.PageBean;
import com.binghe.spring.PaginateInterface;

public interface BookTypeDAO extends Serializable {
 public abstract PaginateInterface getPaginate();

 public abstract PageBean getPageBean();

 public abstract boolean checkBookTypeIsValid(String name) throws Exception;

 public abstract void addBookType(BookType bookType) throws Exception;

 public abstract void updateBookType(BookType bookType) throws Exception;

 public abstract void deleteBookType(Integer id) throws Exception;

 public abstract void deleteAllBookType(String ids[]) throws Exception;

 public abstract BookType findBookTypeById(Integer id) throws Exception;

 public abstract List findAllBookType() throws Exception;

 public abstract List findAllBookType(PageBean page) throws Exception;
}


下面是BookDAOImp中的调用代码:

package com.binghe.spring.booktype;

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

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

import com.binghe.hibernate.booktype.BookType;
import com.binghe.utils.DeptBean;
import com.binghe.spring.PageBean;
import com.binghe.spring.Paginate;
import com.binghe.spring.PaginateInterface;
import com.binghe.utils.UserBean;

public class BookTypeDAOImp extends HibernateDaoSupport implements BookTypeDAO {
 private PaginateInterface paginate;

 private PageBean pageBean = new PageBean();

 public PageBean getPageBean() {
  return pageBean;
 }

 public void setPageBean(PageBean pageBean) {
  this.pageBean = pageBean;
 }

 public PaginateInterface getPaginate() {
  return paginate;
 }

 public void setPaginate(PaginateInterface paginate) {
  this.paginate = paginate;
 }

 public void addBookType(BookType bookType) throws Exception {
  this.getHibernateTemplate().save(bookType);

 }

 public boolean checkBookTypeIsValid(String name) throws Exception {
  String names[] = new String[1];
  names[0] = name;
  boolean valid = false;
  List list = this.getHibernateTemplate().find(
    "select b.id from BookType b where b.name=?", names);
  if (list.size() > 0) {
   valid = true;
  }
  return valid;

 }

 public void updateBookType(BookType bookType) throws Exception {
  this.getHibernateTemplate().update(bookType);

 }

 public BookType findBookTypeById(Integer id) throws Exception {

  String sql = "select b,u.userName,d.deptName "
    + " from BookType b,UserBean u,DeptBean d "
    + " where b.userId=u.OID and u.deptOID=d.OID and b.id=:id";
  List list = this.getHibernateTemplate().findByNamedParam(sql, "id", id);
  Iterator it = list.iterator();
  BookType b = null;
  UserBean u = new UserBean();
  DeptBean d = new DeptBean();
  if (it.hasNext()) {
   Object o[] = (Object[]) it.next();
   b = (BookType) o[0];
   u.setUserName((String) o[1]);
   d.setDeptName((String) o[2]);
   u.setDept(d);
   b.setUser(u);
  }
  return b;
 }

 public List findAllBookType() throws Exception {
  List bookTypes = new ArrayList();

  String sql = "select b,u.userName,d.deptName "
    + " from BookType b,UserBean u,DeptBean d "
    + " where b.userId=u.OID and u.deptOID=d.OID";
  List list = this.getHibernateTemplate().find(sql);
  Iterator it = list.iterator();
  while (it.hasNext()) {
   Object o[] = (Object[]) it.next();
   BookType b = null;
   UserBean u = new UserBean();
   DeptBean d = new DeptBean();
   b = (BookType) o[0];
   u.setUserName((String) o[1]);
   d.setDeptName((String) o[2]);
   u.setDept(d);
   b.setUser(u);
   bookTypes.add(b);
  }
  if (bookTypes.size() > 0)
   return bookTypes;
  return null;
 }

 public List findAllBookType(PageBean p) throws Exception {
  List bookTypes = new ArrayList();

  String sql = "select b,u.userName,d.deptName "
    + " from BookType b,UserBean u,DeptBean d "
    + " where b.userId=u.OID and u.deptOID=d.OID";

  String sql2 = "select count(*) from BookType";
  p.setListSQL(sql);
  p.setTotalCountSQL(sql2);
  p.setCount(this.getPaginate().getTotalCount(p));
  this.setPageBean(p);
  List list = this.getPaginate().getList(p);
  Iterator it = list.iterator();
  while (it.hasNext()) {
   Object o[] = (Object[]) it.next();
   BookType b = null;
   UserBean u = new UserBean();
   DeptBean d = new DeptBean();
   b = (BookType) o[0];
   u.setUserName((String) o[1]);
   d.setDeptName((String) o[2]);
   u.setDept(d);
   b.setUser(u);
   bookTypes.add(b);
  }
  if (bookTypes.size() > 0)
   return bookTypes;
  return null;
 }

 public void deleteBookType(Integer id) throws Exception {
  BookType bookType = (BookType) this.getHibernateTemplate().load(
    BookType.class, id);
  getHibernateTemplate().delete(bookType);
 }

 public void deleteAllBookType(String ids[]) throws Exception {
  List list = new ArrayList();
  for (int i = 0; i < ids.length; i++) {
   BookType bookType = (BookType) this.getHibernateTemplate().load(
     BookType.class, new Integer(ids[i]));
   list.add(i, bookType);
  }
  getHibernateTemplate().deleteAll(list);
 }

}

这是我写的一个项目中抽取的代码,上面全是代码形式没有文字说明,如果有经验的话我觉得会看懂的,看不懂的话可以发表评论。

你可以通过这个链接引用该篇文章:http://huntright.bokee.com/tb.b?diaryId=13342350
分享到:
评论
1 楼 dupx 2007-06-09  
显示分面的页面在脚本是什么啊..

相关推荐

Global site tag (gtag.js) - Google Analytics