jsp使用自定义标签taglib分页系列——PaginationTag.java

15 篇文章 0 订阅

package com.avantouch.common.web.struts.taglib;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import org.apache.commons.collections.IteratorUtils;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.RequestUtils;
import org.apache.struts.util.ResponseUtils;

import com.avantouch.common.web.struts.taglib.table.TableTag;

/**
 * <p>Title PaginationTag.java</p>
 * <p>Description  </p>
 * <p>Copyright:  Copyright (c) 2004 AvanTouch,Inc</p>
 * <p>Company:  AvanTouch,Inc</p>
 * @author:  david 2004-11-30
 * @modifier:
 * @version  1.0
 */
public abstract class PaginationTag extends TableTag {

 public static final String[] FrameValue =
  { "above", "below", "border", "box", "hsides", "lhs", "rhs", "void", "vsides" };

 public static final String[] DirValue = { "ltr", "rtl" };
 public static final String[] RulesValue = { "all", "cors", "groups", "none", "rows" };
 /**
 * The name of the collection or owning bean.
 */
 protected String name = null;

 /**
 * The scope of the bean specified by the name property, if any.
 */
 protected String scope = null;
 /**
  * The action  is required ,link  address(.../XXXXAction.do)
  */
 protected String action = null;
 /**
 * The property name containing the collection.
 */
 protected String property = null;

 /**
  * will jump firsthand page number
  * pageIndexValue=0 don't jump
  */
 private int pageIndexValue = 0;
 /**
  * will jump firsthand page number
  */
 protected String pageCount = null;
 /**
  *  total page count
  */
 protected int totalPageCount = 0;
 /**
  * data record's collection count
  */
 private int totalSize = 0;

 /**
  * per page display data record's count(<=0 means no limit).
  */
 private int perPageCount = 10;

 /**
 * The length value or attribute name (<=0 means no limit).
 */
 protected String length = null;
 /**
  * will display  page number
  */
 protected String currentPage = null;

 private int currentPageValue = 1;

 /**
  * The collection over which we will be iterating.
  */
 private Object collection = null;

 /**
 * Iterator of the elements of this collection, while we are actually
 * running.
 */
 protected Iterator iterator = null;

 /**
 * The message resources for this package.
 */
 protected static MessageResources messages =
  MessageResources.getMessageResources("org.apache.struts.taglib.logic.LocalStrings");
 /**
 * The starting offset (zero relative).
 */
 protected String offset = null;
 /**
 * The actual offset value (calculated in the start tag).
 */
 protected int offsetValue = 0;

 /**
  * isPageCount=true dispaly text for entering pageCount
  * isPageCount=false don't dispaly any text
  */
 protected String isPageCount = null;
 protected boolean displayPageCount = false;

 protected String tableHead = null;

 protected String[] tableheaders = null;

 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getScope() {
  return scope;
 }
 public void setScope(String scope) {
  this.scope = scope;
 }
 public String getProperty() {
  return property;
 }
 public void setProperty(String property) {
  this.property = property;
 }

 public String getAction() {
  return action;
 }
 public void setAction(String action) {
  this.action = action;
 }
 public String getTableHead() {
  return tableHead;
 }

 public void setTableHead(String string) {
  tableHead = string;
 }
 /**
  *
  * <p><code>getCollection</code></p>
  * @return
  * @author david 2004-11-30
  * @Since 1.0
  */
 public Object getCollection() throws JspException {
  if (collection == null) {
   collection = lookupCollection();
  }
  return collection;
 }
 /**
  * find data bean
  * <p><code>lookupCollection</code></p>
  * @return
  * @author david 2004-11-30
  * @Since 1.0
  */
 public Object lookupCollection() throws JspException {
  // Acquire the collection we are going to iterate over
  Object collection = this.collection;
  if (collection == null) {
   collection = RequestUtils.lookup(pageContext, name, property, scope);
  }

  if (collection == null) {
   JspException e = new JspException(messages.getMessage("iterate.collection"));
   RequestUtils.saveException(pageContext, e);
   throw e;
  }
  return collection;
 }

 /**
  *
  * <p><code>init</code></p>
  * @throws JspException
  * @author david 2004-12-2
  * @Since 1.0
  */
 /**
  * init attributes's value
  * <p><code>init</code></p>
  * @throws JspException
  * @author david 2004-12-1
  * @Since 1.0
  */
 private void init() throws JspException {
  Object collection = getCollection();
  // Construct an iterator for this collection
  if (collection.getClass().isArray()) {
   try {
    // If we're lucky, it is an array of objects
    // that we can iterate over with no copying
    totalSize = ((Object[]) collection).length;
    iterator = Arrays.asList((Object[]) collection).iterator();
   } catch (ClassCastException e) {
    // Rats -- it is an array of primitives
    int length = Array.getLength(collection);
    ArrayList c = new ArrayList(length);
    for (int i = 0; i < length; i++) {
     c.add(Array.get(collection, i));
    }
    totalSize = c.size();
    iterator = c.iterator();
   }
  } else if (collection instanceof Collection) {
   iterator = ((Collection) collection).iterator();
   totalSize = ((Collection) collection).size();
  } else if (collection instanceof Iterator) {
   iterator = (Iterator) collection;
   totalSize = getTotal(iterator);
  } else if (collection instanceof Map) {
   iterator = ((Map) collection).entrySet().iterator();
   totalSize = ((Map) collection).size();
  } else if (collection instanceof Enumeration) {
   iterator = IteratorUtils.asIterator((Enumeration) collection);
   totalSize = getTotal(iterator);
  } else {
   JspException e = new JspException(messages.getMessage("iterate.iterator"));
   RequestUtils.saveException(pageContext, e);
   throw e;
  }
  if (tableHead != null && tableHead.trim().equals("")) {   
   totalSize = totalSize - 1;
   if (totalSize < 0)
    totalSize = 0;
  }
  if(tableHead!=null&&tableHead.trim().equals("tableHead")){
   tableHead=(String) RequestUtils.lookup(pageContext, tableHead, null);
  }
  // compute perPageCount's  value
  if (length != null) {
   try {
    perPageCount = Integer.parseInt(length);
   } catch (NumberFormatException e) {
    Integer lengthObject = (Integer) RequestUtils.lookup(pageContext, length, null);
    if (lengthObject == null) {
     perPageCount = 10;
    } else {
     perPageCount = lengthObject.intValue();
    }
   }
  } // end if
  // Calculate the starting offset
  if (offset == null) {
   offsetValue = 0;
  } else {
   try {
    offsetValue = Integer.parseInt(offset);
   } catch (NumberFormatException e) {
    Integer offsetObject = (Integer) RequestUtils.lookup(pageContext, offset, null);
    if (offsetObject == null) {
     offsetValue = 0;
    } else {
     offsetValue = offsetObject.intValue();
    }
   }
  }
  if (offsetValue < 0) {
   offsetValue = 0;
  }

  if (pageCount == null) {
   try {
    pageCount = lookup("pageCount", null).toString();
   } catch (Exception e) {
   }
  }
  if (currentPage == null) {
   try {
    currentPage = lookup("currentPage", null).toString();
   } catch (Exception e) {
   }
  }
  // compute pageIndexValue's value
  if (pageCount != null && !pageCount.trim().equals("")) {
   try {
    pageIndexValue = Integer.parseInt(pageCount);
   } catch (NumberFormatException e) {
    Integer pageIndex = (Integer) RequestUtils.lookup(pageContext, pageCount, null);
    if (pageIndex == null) {
     pageIndexValue = 1;
    } else {
     pageIndexValue = pageIndex.intValue();
    }
   }
   if (pageIndexValue > getTotalPageCount() || pageIndexValue < 0) {
    pageIndexValue = this.totalPageCount;
   }
  } else {
   this.totalPageCount = getTotalPageCount();
  } // end if

  //compute currentPageValue's  value
  if (currentPage != null) {
   try {
    currentPageValue = Integer.parseInt(currentPage);
   } catch (NumberFormatException e) {
    Integer currentObejct = (Integer) RequestUtils.lookup(pageContext, currentPage, null);
    if (currentObejct == null) {
     currentPageValue = 1;
    } else {
     currentPageValue = currentObejct.intValue();
    }
   }
  } // end if

  if (isPageCount != null) {
   displayPageCount = Boolean.valueOf(isPageCount).booleanValue();
  }

 } // end init

 /**
  *  init attribute iterator's value
  * <p><code>initIterator</code></p>
  * @return
  * @throws JspException
  * @author david 2004-12-1
  * @Since 1.0
  */
 private Iterator initIterator() throws JspException {

  if (pageIndexValue > 0) {
   currentPageValue = pageIndexValue;
  }
  if (currentPageValue < 1)
   currentPageValue = 1;
  if (currentPageValue > (totalPageCount - offsetValue / perPageCount))
   currentPageValue = totalPageCount - offsetValue / perPageCount;

  this.currentPage = String.valueOf(currentPageValue);

  pageIndexValue = currentPageValue;
  if (tableHead != null && tableHead.trim().equals("")) {
   if (iterator.hasNext()) {
    tableheaders = (String[]) iterator.next();
   }
  } else if (tableHead != null) {
   tableheaders = tableHead.trim().split(",");
  }
  for (int i = 0; i < ((currentPageValue - 1) * this.perPageCount + offsetValue); i++) {
   if (iterator.hasNext()) {
    iterator.next();
   } else {
    break;
   }
  }
  return iterator;

 }

 /**
  * init all attributes's value
  * <p><code>initAllAttribute</code></p>
  * @throws JspException
  * @author david 2004-12-1
  * @Since 1.0
  */
 public void initAllAttribute() throws JspException {
  init();
  this.iterator = initIterator();
  if (getStyleClass1_TR() != null
   && getStyleClass2_TR() != null
   && !getStyleClass1_TR().trim().equals("")
   && !getStyleClass2_TR().trim().equals("")) {
   pageContext.setAttribute("TRCALSS1", getStyleClass1_TR());
   pageContext.setAttribute("TRCALSS2", getStyleClass2_TR());
   pageContext.setAttribute("currentTRCLASS", "0");
  }
 }

 public int doStartTag() throws JspException {
  initAllAttribute();
  if (iterator.hasNext()) {
   writePaginationInTable();
   return (EVAL_BODY_BUFFERED);
  } else {
   return (SKIP_BODY);
  }
 }

 public int doEndTag() throws JspException {
  StringBuffer buf = new StringBuffer("</TABLE>/n");
  ResponseUtils.write(pageContext, buf.toString());
  release();
  // Continue processing this page
  return (EVAL_PAGE);
 }

 /**
  * write pagination information
  * <p><code>writePaginationInTable</code></p>
  * @throws JspException
  * @author david 2004-12-1
  * @Since 1.0
  */
 public void writePaginationInTable() throws JspException {

  validateFrame();
  validateDir();
  validateRules();

  String prefixPath = ((HttpServletRequest) pageContext.getRequest()).getContextPath();
  StringBuffer buf = new StringBuffer("<TABLE");
  // setT_ID(buf);
  setTablePagintionAttributes(buf);
  // prepareEvents_T(buf);  
  buf.append(">/n");
  //buf=setTableCaption(buf);
  buf.append(" <TR nowrap>/n");
  buf.append(
   "  <TD valign='top'><img id='btn' border='0' width='17' height='17' src='"
    + prefixPath
    + "/images/corners/l.gif'></TD>/n");
  buf = AddRecordInfoByNumber(buf);
  //or buf=AddRecordInfoByPageCount(buf);

  buf.append("  <TD WIDTH=/"100%/">&nbsp;</TD>/n");
  buf = writeDisplayPageCount(buf);
  buf = AddPageLink(buf);
  buf.append(
   "  <TD valign='top'><img id='btn' border='0' width='17' height='17' src='"
    + prefixPath
    + "/images/corners/r.gif'></TD>/n");
  buf.append(" </TR>/n");

  buf.append("</TABLE>/n");
  String output = buf.toString();
  ResponseUtils.write(pageContext, output);
 } // end writePaginationInTable

 /**
  *  set pagintion table attributes
  * <p><code>setTablePagintionAttributes</code></p>
  * @param buffer
  * @return
  * @author david 2004-12-3
  * @Since 1.0
  */
 private void setTablePagintionAttributes(StringBuffer buffer) {
  String tempborder = getBorder();
  String tempcellPadding = getCellPadding();
  String tempcellSpacing = getCellSpacing();
  String tempstyleClass = getStyleClass();
  String tempstyle = getStyle();

  setBorder("0");
  setCellPadding("0");
  setCellSpacing("0");
  setStyleClass("lch");
  setStyle(null);

  setTableCommonAttributes(buffer);

  setBorder(tempborder);
  setCellPadding(tempcellPadding);
  setCellSpacing(tempcellSpacing);
  setStyleClass(tempstyleClass);
  setStyle(tempstyle);
 } // end setTablePagintionAttributes

 /**
  * add record number information
  * <p><code>AddRecordInfoByNumber</code></p>
  * @param buffer
  * @return
  * @author david 2004-12-1
  * @Since 1.0
  */
 public StringBuffer AddRecordInfoByNumber(StringBuffer buffer) {
  StringBuffer buf = buffer;
  // add illustrative worlds
  buf.append("  <TD nowrap class=/"c/">");
  if (getTitle() != null && !getTitle().trim().equals("")) {
   buf.append(getTitle() + " ");
  }
  buf.append("current page record : </TD>/n");
  buf.append("  <TD nowrap class=/"d/">");
  buf.append((currentPageValue - 1) * this.perPageCount + 1 + offsetValue);
  int endIndex = currentPageValue * this.perPageCount + offsetValue;
  if (endIndex > this.totalSize)
   endIndex = this.totalSize;
  buf.append("  to  " + endIndex);
  buf.append(" of " + this.totalSize);
  buf.append("</TD>/n");

  return buf;
 } // end AddRecordInfoByNumber

 /**
  * add record page count information
  * <p><code>AddRecordInfoByPageCount</code></p>
  * @param buffer
  * @return
  * @author david 2004-12-1
  * @Since 1.0
  */
 public StringBuffer AddRecordInfoByPageCount(StringBuffer buffer) {
  StringBuffer buf = buffer;
  // add illustrative worlds
  buf.append("  <TD nowrap nowrap class=/"c/">");
  if (getTitle() != null && !getTitle().trim().equals("")) {
   buf.append(getTitle() + " ");
  }
  buf.append("current page number : </TD>/n");
  buf.append("  <TD nowrap class=/"d/">");
  buf.append(currentPageValue);
  buf.append(" of " + this.totalPageCount);
  buf.append("</TD>/n");
  return buf;
 } // end AddRecordInfoByPageCount

 /**
  * add page common link
  * <p><code>AddPageLink</code></p>
  * @param buffer
  * @return
  * @author david 2004-12-1
  * @Since 1.0
  */
 public StringBuffer AddPageLink(StringBuffer buffer) {
  String prefixPath = ((HttpServletRequest) pageContext.getRequest()).getContextPath();
  StringBuffer buf = buffer;
  buf.append("  <TD>");
  buf.append("<A href=/"" + getAction());
  buf.append("?method=Create&currentPage=" + currentPage + "/"");
  buf.append(" title=/"create new item/">");
  buf.append(
   "<img id='btn' border='0' width='15' height='15' src='" + prefixPath + "/images/buttons/btnCreate1.gif'>");
  buf.append("</A>");
  buf.append("</TD>/n");

  buf.append("  <TD>");
  buf.append("<A href=/"" + getAction());
  buf.append("?method=Refresh&currentPage=" + currentPage + "/"");
  buf.append(" title=/"refresh page/">");
  buf.append(
   "<img id='btn' border='0'  width='15' height='15' src='"
    + prefixPath
    + "/images/buttons/btnRefresh1.gif'>");
  buf.append("</A>");
  buf.append("</TD>/n");

  if (currentPageValue > 1) {
   buf.append("  <TD>");
   buf.append("<A href=/"" + getAction());
   buf.append("?method=Page&currentPage=1/"");
   buf.append(" title=/"goto first page/">");
   buf.append(
    "<img id='btn' border='0'  width='15' height='15' src='"
     + prefixPath
     + "/images/buttons/btnFirst1.gif'>");
   buf.append("</A>");
   buf.append("</TD>/n");

   buf.append("  <TD>");
   buf.append("<A href=/"" + getAction());
   buf.append("?method=Page&currentPage=" + (currentPageValue - 1) + "/"");
   buf.append(" title=/"goto previous page/">");

   buf.append(
    "<img id='btn' border='0' width='15' height='15' src='"
     + prefixPath
     + "/images/buttons/btnPrev1.gif'>");
   buf.append("</A>");
   buf.append("</TD>/n");
  } else {
   buf.append("  <TD>");
   buf.append(
    "<img id='btn' border='0' width='15' height='15' src='"
     + prefixPath
     + "/images/buttons/btnFirst2.gif'>");
   buf.append("</TD>/n");
   buf.append("  <TD>");
   buf.append(
    "<img id='btn' border='0' width='15' height='15' src='"
     + prefixPath
     + "/images/buttons/btnPrev2.gif'>");
   buf.append("</TD>/n");
  }
  if (currentPageValue < (totalPageCount - offsetValue / perPageCount)) {
   buf.append("  <TD>");
   buf.append("<A href=/"" + getAction());
   buf.append("?method=Page&currentPage=" + (currentPageValue + 1) + "/"");
   buf.append(" title=/"goto next page/">");
   buf.append(
    "<img id='btn' border='0' width='15' height='15' src='"
     + prefixPath
     + "/images/buttons/btnNext1.gif'>");
   buf.append("</A>");
   buf.append("</TD>/n");

   buf.append("  <TD>");
   buf.append("<A href=/"" + getAction());
   buf.append("?method=Page&currentPage=" + (totalPageCount - offsetValue / perPageCount) + "/"");
   buf.append(" title=/"goto last page/">");
   buf.append(
    "<img id='btn' border='0' width='15' height='15' src='"
     + prefixPath
     + "/images/buttons/btnLast1.gif'>");
   buf.append("</A>");
   buf.append("</TD>/n");
  } else {
   buf.append("  <TD>");
   buf.append(
    "<img id='btn' border='0' width='15' height='15' src='"
     + prefixPath
     + "/images/buttons/btnNext2.gif'>");
   buf.append("</TD>/n");
   buf.append("  <TD>");
   buf.append(
    "<img id='btn' border='0' width='15' height='15' src='"
     + prefixPath
     + "/images/buttons/btnLast2.gif'>");
   buf.append("</TD>/n");
  }
  return buf;
 } // end AddPageLink

 public StringBuffer writeDisplayPageCount(StringBuffer buffer) {
  StringBuffer buf = buffer;
  if (isDisplayPageCount()) {
   buf.append(
    "  <TD valign='middle' nowrap><INPUT TYPE='button' value='GOTO' οnclick=/"gotoPageCount('");
   buf.append(getAction() + "?method=Page&currentPage=" + currentPage);
   buf.append("')/" style='height:17; border:0; '/><INPUT TYPE='text' name='pageCount' value='");
   if (pageIndexValue != 0) {
    buf.append(pageIndexValue);
   }
   buf.append("' size='4' style='height:17; border:0;'/> <EM>Page&nbsp;</EM></TD>/n");
  }
  return buf;
 }
 /**
  * compute  total page count
  * <p><code>getTotalPageCount</code></p>
  * @return
  * @author david 2004-11-30
  * @Since 1.0
  */
 public int getTotalPageCount() {
  if (perPageCount == 0 || totalSize == 0)
   return 0;
  if (totalPageCount > 0)
   return totalPageCount;

  totalPageCount = totalSize / perPageCount;
  if (totalSize % perPageCount != 0)
   totalPageCount = totalPageCount + 1;

  return totalPageCount;
 }

 /**
  *
  * <p><code>getTotal</code></p>
  * @param iterator
  * @return
  * @author david 2004-11-30
  * @Since 1.0
  */
 private int getTotal(Iterator iterator) {
  int count = IteratorUtils.toArray(iterator).length;
  return count;
 }
 /**
  *
  * <p><code>getCurrentPage</code></p>
  * @return
  * @author david 2004-11-30
  * @Since 1.0
  */
 public String getCurrentPage() {
  return currentPage;
 }

 /**
  *
  * <p><code>getPageIndex</code></p>
  * @return
  * @author david 2004-11-30
  * @Since 1.0
  */
 public int getPageIndexValue() {
  return pageIndexValue;
 }

 /**
  *
  * <p><code>getPerPageCount</code></p>
  * @return
  * @author david 2004-11-30
  * @Since 1.0
  */
 public int getPerPageCount() {
  return perPageCount;
 }
 /**
  *
  * <p><code>setCollection</code></p>
  * @param object
  * @author david 2004-11-30
  * @Since 1.0
  */
 public void setCollection(Object object) {
  collection = object;
 }

 /**
  *
  * <p><code>setCurrentPage</code></p>
  * @param i
  * @author david 2004-11-30
  * @Since 1.0
  */
 public void setCurrentPage(String currentPage) {
  this.currentPage = currentPage;
 }

 /**
  *
  * <p><code>setPerPageCount</code></p>
  * @param i
  * @author david 2004-11-30
  * @Since 1.0
  */
 public void setPerPageCount(int i) {
  perPageCount = i;
 }

 /**
  *
  * <p><code>getIterator</code></p>
  * @return
  * @author david 2004-11-30
  * @Since 1.0
  */
 public Iterator getIterator() {
  return iterator;
 }

 /**
  *
  * <p><code>setIterator</code></p>
  * @param iterator
  * @author david 2004-11-30
  * @Since 1.0
  */
 public void setIterator(Iterator iterator) {
  this.iterator = iterator;
 }

 /**
 * Release all allocated resources.
 */
 public void release() {

  super.release();
  iterator = null;
  collection = null;
  pageIndexValue = 0;
  totalPageCount = 0;
  perPageCount = 10;
  currentPage = null;
  totalSize = 0;
  pageCount = null;
  length = null;
  currentPageValue = 1;
  offset = null;
  offsetValue = 0;
  isPageCount = null;
  displayPageCount = false;
  tableHead = null;
  tableheaders = null;
 }

 public static MessageResources getMessages() {
  return messages;
 }

 public String getPageCount() {
  return pageCount;
 }

 public static void setMessages(MessageResources resources) {
  messages = resources;
 }
 public void setPageCount(String string) {
  pageCount = string;
 }

 public String getLength() {
  return length;
 }

 public void setLength(String length) {
  this.length = length;
 }

 public int getCurrentPageValue() {
  return currentPageValue;
 }

 public int getTotalSize() {
  return totalSize;
 }

 public void setCurrentPageValue(int i) {
  currentPageValue = i;
 }
 public void setTotalSize(int i) {
  totalSize = i;
 }

 public String getOffset() {
  return offset;
 }

 public int getOffsetValue() {
  return offsetValue;
 }

 public void setOffset(String offset) {
  this.offset = offset;
 }

 public void setOffsetValue(int i) {
  offsetValue = i;
 }

 public Object lookup(String name, String scope) {
  Object bean = null;
  HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
  if (scope == null) {
   bean = request.getParameter(name);
   if (bean == null)
    bean = request.getAttribute(name);
  } else if (scope.equalsIgnoreCase("request")) {
   bean = request.getAttribute(name);
  } else if (scope.equalsIgnoreCase("session")) {
   bean = request.getSession().getAttribute(name);
  } else if (scope.equals("application")) {
   pageContext.getServletContext().getAttribute(name);
  }
  return bean;
 }

 public boolean isDisplayPageCount() {
  return displayPageCount;
 }

 public String getIsPageCount() {
  return isPageCount;
 }

 public void setDisplayPageCount(boolean b) {
  displayPageCount = b;
 }

 public void setIsPageCount(String isPageCount) {
  this.isPageCount = isPageCount;
 }

} // end PaginationTag
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值