Struts+hibernate实现分页程序
来源:互联网 发布:怎样判断两个矩阵相似 编辑:程序博客网 时间:2024/06/04 08:29
Struts+hibernate实现分页程序
Pager.java文件代码:
package com.shisoft.Pager;
public class Pager {
private int totalRows = 0;// 记录总数
private int totalPages = 0; // 总页数
private int pageSize = 10;// 每页显示数据条数,默认为10条记录
private int currentPage = 1; // 当前页数
private boolean hasPrevious = false; // 是否有上一页
private boolean hasNext = false; // 是否有下一页
public Pager() {
}
/**
* Initialize Pager
*
* @param totalRows
* totalrecord rows
* @param pageSize
* totalrecord is hold by every page
*/
public void init(int totalRows, int pageSize) {
this.totalRows = totalRows;
this.pageSize = pageSize;
totalPages = ((totalRows + pageSize) - 1) / pageSize;
refresh(); // 刷新当前页面信息
}
/**
*
* @return Returns thecurrentPage.
*
*/
public int getCurrentPage() {
return currentPage;
}
/**
*
* @param currentPagecurrent
* page
*
*/
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
refresh();
}
/**
*
* @return Returns thepageSize.
*
*/
public int getPageSize() {
return pageSize;
}
/**
*
* @param pageSize
* ThepageSize to set.
*
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
refresh();
}
/**
*
* @return Returns thetotalPages.
*
*/
public int getTotalPages() {
return totalPages;
}
/**
*
* @param totalPages
* ThetotalPages to set.
*
*/
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
refresh();
}
/**
*
* @return Returns thetotalRows.
*
*/
public int getTotalRows() {
return totalRows;
}
/**
*
* @param totalRows
* ThetotalRows to set.
*
*/
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
refresh();
}
// 跳到第一页
public void first() {
currentPage = 1;
this.setHasPrevious(false);
refresh();
}
// 取得上一页(重新设定当前页面即可)
public void previous() {
currentPage--;
refresh();
}
// 取得下一页
public void next() {
if (currentPage < totalPages) {
currentPage++;
}
refresh();
}
public void doAction(String action) {
if (action != null) {
// 根据传递进来的参数控制页面的前进后退
if (action.equalsIgnoreCase("previous")) {
this.previous();
} else if (action.equalsIgnoreCase("next")) {
this.next();
} else if (action.equalsIgnoreCase("first")) {
this.first();
} else if (action.equalsIgnoreCase("last")) {
this.last();
} else {
this.setCurrentPage(Integer.parseInt(action));
}
}
}
// 跳到最后一页
public void last() {
currentPage = totalPages;
this.setHasNext(false);
refresh();
}
public boolean isHasNext() {
return hasNext;
}
/**
*
* @param hasNext
* ThehasNext to set.
*
*/
public void setHasNext(boolean hasNext) {
this.hasNext = hasNext;
}
public boolean isHasPrevious() {
return hasPrevious;
}
/**
*
* @param hasPrevious
* ThehasPrevious to set.
*
*/
public void setHasPrevious(boolean hasPrevious) {
this.hasPrevious = hasPrevious;
}
// 刷新当前页面信息
public void refresh() {
if (totalPages <= 1) {
hasPrevious = false;
hasNext = false;
} else if (currentPage == 1) {
hasPrevious = false;
hasNext = true;
} else if (currentPage == totalPages) {
hasPrevious = true;
hasNext = false;
} else {
hasPrevious = true;
hasNext = true;
}
}
}
分页标签:PagerTag.java
package com.shisoft.Pager;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
/**
* 通用分页标签的处理类
*/
public class PagerTag extends TagSupport {
private String value = "";
private String url = "";
private String pagerStr="";
JspWriter out = null;
public int doStartTag() throws JspException {
try {
out = pageContext.getOut();
} catch (Exception e) {
e.printStackTrace();
}
BuildPagerBar();
return SKIP_BODY;
}
public int doEndTag() {
return EVAL_PAGE;
}
private void BuildPagerBar() {
Pager pager = (Pager) pageContext.getSession().getAttribute(pagerStr);
StringBuffer toolbar = new StringBuffer();
toolbar
.append("<table table align='center' title='通用分页标签' width='100%' align='center' cellpadding='0' cellspacing='0' style='FONT-SIZE:
toolbar.append("<tr>");
toolbar.append("<td width=60% >共");
toolbar.append(new Integer(pager.getTotalRows()).toString());
toolbar.append("条记录 第");
toolbar.append(new Integer(pager.getCurrentPage()).toString());
toolbar.append("/");
toolbar.append(new Integer(pager.getTotalPages()).toString());
toolbar.append("页</td>");
toolbar.append("<td align=right width=5%>");
toolbar.append("<a href='");
toolbar.append(url);
toolbar.append("?action=first'>首页</a>");
toolbar.append("</td>");
toolbar.append("<td align='center' width='10%'>");
if (pager.isHasPrevious()) {
toolbar.append("<a href='");
toolbar.append(url);
toolbar.append("?action=previous'>上一页</a>");
} else {
toolbar.append("上一页");
}
toolbar.append("|");
if (pager.isHasNext()) {
toolbar.append("<a href='");
toolbar.append(url);
toolbar.append("?action=next'>下一页</a>");
} else {
toolbar.append("下一页");
}
toolbar.append("</td>");
toolbar.append("<td align=left width=5%>");
toolbar.append("<a href='");
toolbar.append(url);
toolbar.append("?action=last'>末页</a>");
toolbar.append("</td>");
toolbar.append(" <td align='center' width=20%>");
toolbar.append("<FORM action='" + url + "'>");
toolbar.append("跳转到" + "<input name='action' size='3' />");
toolbar.append("<INPUT type='submit' value='GO'/>");
toolbar.append("</FORM>");
toolbar.append("</td>");
toolbar.append("</tr></table>");
try {
out.println(toolbar.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
/**
* @return the pagerStr
*/
public String getPagerStr() {
return pagerStr;
}
/**
* @param pagerStr the pagerStr to set
*/
public void setPagerStr(String pagerStr) {
this.pagerStr = pagerStr;
}
}
分页标签的tld文件:mylib.tld
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>utiltag</shortname>
<uri>http://beltino.com/util</uri>
<tag>
<name>pager</name>
<tagclass>com.shisoft.Pager.PagerTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>url</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>pagerStr</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
实体bean:Bookand.java
package com.shisoft.bean;
/**
* Bookand generated by MyEclipse Persistence Tools
*/
public class Bookand implements java.io.Serializable {
// Fields
private Integer id;
private String bookname;
private String author;
private Double price;
// Constructors
/** default constructor */
public Bookand() {
}
/** full constructor */
public Bookand(String bookname, String author, Double price) {
this.bookname = bookname;
this.author = author;
this.price = price;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBookname() {
return this.bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public String getAuthor() {
return this.author;
}
public void setAuthor(String author) {
this.author = author;
}
public Double getPrice() {
return this.price;
}
public void setPrice(Double price) {
this.price = price;
}
}
实体操作类:dao文件
package com.shisoft.bean;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
/**
* Data access object (DAO) for domain model class Bookand.
*
* @see com.shisoft.bean.Bookand
* @author MyEclipse Persistence Tools
*/
public class BookandDAO extends BaseHibernateDAO {
private static final Log log = LogFactory.getLog(BookandDAO.class);
// property constants
public static final String BOOKNAME = "bookname";
public static final String AUTHOR = "author";
public static final String PRICE = "price";
public void save(Bookand transientInstance) {
log.debug("saving Bookand instance");
try {
getSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(Bookand persistentInstance) {
log.debug("deleting Bookand instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Bookand findById(java.lang.Integer id) {
log.debug("getting Bookand instance with id: " + id);
try {
Bookand instance = (Bookand) getSession().get(
"com.shisoft.bean.Bookand", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(Bookand instance) {
log.debug("finding Bookand instance by example");
try {
List results = getSession().createCriteria(
"com.shisoft.bean.Bookand").add(Example.create(instance))
.list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding Bookand instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Bookand as model where model."
+ propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByBookname(Object bookname) {
return findByProperty(BOOKNAME, bookname);
}
public List findByAuthor(Object author) {
return findByProperty(AUTHOR, author);
}
public List findByPrice(Object price) {
return findByProperty(PRICE, price);
}
public List findAll() {
log.debug("finding all Bookand instances");
try {
Session s=getSession();
String queryString = "from Bookand";
Query queryObject = s.createQuery(queryString);
List l=queryObject.list();
return l;
} catch (RuntimeException re) {
re.printStackTrace();
log.error("find all failed", re);
throw re;
}
}
public List findAllByPage(int firstrows,int pagesize) {
log.debug("finding all Bookand instances");
try {
Session s=getSession();
String queryString = "from Bookand";
Query queryObject = s.createQuery(queryString);
queryObject.setMaxResults(pagesize);
queryObject.setFirstResult(firstrows);
List l=queryObject.list();
return l;
} catch (RuntimeException re) {
re.printStackTrace();
log.error("find all failed", re);
throw re;
}
}
public Bookand merge(Bookand detachedInstance) {
log.debug("merging Bookand instance");
try {
Bookand result = (Bookand) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Bookand instance) {
log.debug("attaching dirty Bookand instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Bookand instance) {
log.debug("attaching clean Bookand instance");
try {
getSession().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public static void main(String [] args){
BookandDAO dao = new BookandDAO();
System.out.println("-=----");
List results = dao.findAll();
System.out.println(results.size());
for (int i=0;i<results.size();i++) {
Bookand bookand=new Bookand();
System.out.println("===========");
System.out.println(bookand.getBookname());
}
}
}
Action中代码:
package com.shisoft.struts.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.shisoft.Pager.Pager;
import com.shisoft.bean.BookandDAO;
public class PagerAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response){
Pager pager=null;
BookandDAO dao = new BookandDAO();
List results = dao.findAll();
try {
if (request.getSession().getAttribute("pagerstruts") == null) {
pager = new Pager();
int totalRows =results.size();
pager.init(totalRows,3);
} else {
pager = (Pager) request.getSession().getAttribute("pagerstruts");
}
if (request.getParameter("action") != null) {
pager.doAction(request.getParameter("action").toString());
}
List list = dao.findAllByPage((pager.getCurrentPage() - 1)* pager.getPageSize(),pager.getPageSize());
request.getSession().setAttribute("pagerstruts",pager);
request.setAttribute("list", list);
} catch (Exception re) {
re.printStackTrace();
}
return mapping.findForward("success");
}
}
Jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="/WEB-INF/mylib.tld" prefix="pager"%>
<html>
<head>
<title>分页</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">
-->
</head>
<body>
<table width="100%" align="center" border="1" cellpadding="0"
cellspacing="0" bordercolor="#ffc
<tr>
<td align="center">
书名
</td>
<td align="center">
作者
</td>
<td align="center">
价钱
</td>
</tr>
<logic:iterate id="u" name="list">
<tr>
<td>
<bean:write name="u" property="bookname" />
</td>
<td align="center">
<bean:write name="u" property="author" />
</td>
<td align="center">
<bean:write name="u" property="price" />
</td>
</tr>
</logic:iterate>
<tr>
<td colspan="3">
<pager:pager value="pager" url="pager.do" pagerStr="pagerstruts"/>
</td>
</tr>
</table>
</body>
</html>
Struts配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="pagerForm" type="com.shisoft.struts.form.PagerForm" />
</form-beans>
<global-exceptions />
<global-forwards>
<forward name="pager" path="/pager.do"></forward>
</global-forwards>
<action-mappings>
<action path="/pager"
type="com.shisoft.struts.action.PagerAction"
scope="request">
<forward name="success"
path="/ok.jsp"></forward>
</action>
</action-mappings>
<message-resources parameter="com.shisoft.struts.ApplicationResources" />
</struts-config>
- Struts+hibernate实现分页程序
- Struts+hibernate实现分页程序
- Struts + Hibernate 实现 分页
- Struts+Hibernate 分页实现
- struts+hibernate分页实现
- Struts+Hibernate实现分页
- Struts+Hibernate实现分页
- Struts+Hibernate分页的实现
- struts+hibernate 分页的实现
- Struts+Hibernate实现分页功能
- Struts+Hibernate开发实践 分页的实现
- Struts+Hibernate开发实践 分页的实现
- Struts+Hibernate开发实践 分页的实现
- Struts+Hibernate开发实践 分页的实现
- Struts+Hibernate开发实践 分页的实现
- hibernate+spring实现分页程序
- 分页 STRUTS+HIBERNATE+ORACLE分页
- STRUTS+HIBERNATE+ORACLE分页
- 如何取得一个月的最大天数和最小天数
- tolua++初探(二)
- 暴力破解!ioffice.net 政务系统安装
- Oracle中对像名大小写敏感性的深入解析
- Spring中正确使用Quartz和CronExpression
- Struts+hibernate实现分页程序
- DOM常用属性小结(z)
- socket I/O models
- 如何为 MFC 应用程序创建本地化资源 DLL
- 继续joke
- Filter介绍
- c++强制类型转换
- 存储过程例子
- iemnaw.dll为无效映像?毒霸瑞星也玩失踪?原来中了Win32.Logogo,RootKit.Win32.HideFile等1