`
weishaoying
  • 浏览: 4470 次
社区版块
存档分类
最新评论

原创技术:史上最灵活,强大的分页框架

阅读更多

这个框架具有以下优点:

 

1.提供了各种常用的输入方式,如:可以输入页码跳转、可以通过下拉列表跳转、可以通过上、下页按钮跳转还支持类似百度式的分页风格。
2.前台js已实现对用户的输入进行校验,比如用户输入的页码超过了最大值,会自动纠正并提示,页码的正则表达式校验等。
3.可以支持在一个页面中无数多个分页组件
4.使用简单、只需要在页面中像写struts标签一样写一个标签即可,不需引入任何jsp文件也不用拷贝任何js代码,输入时还有提示
5.可以随意定制显示那些组件如,只要按钮,只要下拉列表等,以及按钮样式、谷歌风格分页时显示多少个页码数等任何一个属性,用户都可以控制,而代价仅仅是标签中的一个属性。
6.支持业界主流的Struts2

7.最大的优点就是灵活,可以配置,而且仅仅需要在jsp中修改属性的值即可完成UI的变化,如可以设置当前页为第一页时,首页是否置灰,百度风格的分页显示页码为奇数还是偶数,如果是奇数则当前页处于中间,如果是偶数则当前页处于1/2总页码+0.5,还是1/2总页码-0.5,button样式可以配置,自己写好程序后让美工美化。由于分页信息较多,可以将其单独作为一行,将功能按钮放在页面的左上方即美观操作又方便。

 

 

 

 

见效果: 

 

 

 

包括各种分页信息:总条数、总页数、当前页数、每页多少条

 

 

 

 



 

来个复杂的:经过我的测试怎么玩都可以!!

 

 

 

 

 

 

 

 

 这里经常图片出不来,重新传一张

 分页中常用的各种控件都有了,并且可以根据自己的需求设置使用哪些控件,以及控件的css样式

 

 

 

 

这样以后在开发分页时就非常简单了,并且在IDE中还有自动提示:

 

 

 

 

 

下面附上实现方式(采用从表至里的顺序介绍,下面是我2011年写的一个小demo):

 

 1.自定义Tag

package com.lenovo.quartz.foundation.tag;

import java.io.IOException;
import java.util.Random;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.lenovo.quartz.foundation.constant.Constants;
import com.lenovo.quartz.foundation.util.StringUtil;

/**
 * PageTag.java
 *
 * Description:
 *
 * @Copyright: Copyright(c)2011 Weishaoying. All right reserved.
 * @author: WeiShaoying
 * @Mail: weishaoying-99@163.com
 * @version: 1.0
 * @date: 2010-10-6
 *
 */

public class PageTag extends TagSupport {
 
 private static final long serialVersionUID = -8872350470776156135L;

 private Integer totalDataSize;

 private Integer currentPageNo;

 private Integer pageSize;
 
 //form id
 private String formId;

 private String btnClass;

 private String inputClass;

 private String selClass;

 private String queryParams;

 
 private boolean psiEnable = Constants.PSI_COMPONENT_ENABLE;

 private boolean pniEnable = Constants.PNI_COMPONENT_ENABLE;

 private boolean pnsEnable = Constants.PNS_COMPONENT_ENABLE;

 private boolean pngEnable = Constants.PNG_COMPONENT_ENABLE;
 
 private boolean pnbEnable = Constants.PNB_COMPONENT_ENABLE;
 
 private Integer pnShowNum;
 
 //
 private boolean headTailDisable;
 
 //private Integer firstResult;
 
 //private Integer lastResult;
 


 public Integer getTotalPageSize() {
  return (this.totalDataSize + pageSize - 1) / pageSize;
 }
 
 public Integer getTopPageNo() {
  return 1;
 }

 public Integer getPrevPageNo() {
  return currentPageNo > 1 ? (currentPageNo - 1) : 1;
 }

 //
 public Integer getNextPageNo() {
  return currentPageNo < getTotalPageSize() ? (currentPageNo + 1) : getTotalPageSize();
 }

 //
 public Integer getLastPageNo() {
  return getTotalPageSize();
 }
 
 // 最小是1
 public Integer getFirstResult() {
  return (currentPageNo - 1) * pageSize + 1;
 }

 // 最大不能超过总条数
 public Integer getLastResult() {
  return Math.min(currentPageNo * pageSize, totalDataSize);
 }

 public void setTotalDataSize(Integer totalDataSize) {
  this.totalDataSize = totalDataSize;
 }

 public void setCurrentPageNo(Integer currentPageNo) {
  this.currentPageNo = currentPageNo;
 }

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

 public void setBtnClass(String btnClass) {
  this.btnClass = btnClass;
 }

 public void setInputClass(String inputClass) {
  this.inputClass = inputClass;
 }

 public void setSelClass(String selClass) {
  this.selClass = selClass;
 }

 public void setFormId(String formId) {
  this.formId = formId;
 }

 public void setQueryParams(String queryParams) {
  this.queryParams = queryParams;
 }
 
 public void setPsiEnable(boolean psiEnable) {
  this.psiEnable = psiEnable;
 }
 
 public void setPniEnable(boolean pniEnable) {
  this.pniEnable = pniEnable;
 }
 
 public void setPnsEnable(boolean pnsEnable) {
  this.pnsEnable = pnsEnable;
 }

 public void setPngEnable(boolean pngEnable) {
  this.pngEnable = pngEnable;
 }

 public void setPnShowNum(Integer pnShowNum) {
  this.pnShowNum = pnShowNum;
 }

 public void setHeadTailDisable(boolean headTailDisable) {
  this.headTailDisable = headTailDisable;
 }
 
 public void setPnbEnable(boolean pnbEnable) {
  this.pnbEnable = pnbEnable;
 }
 
 @Override
 public int doStartTag() throws JspException {
  StringBuilder builder = new StringBuilder();
  float random = new Random().nextFloat();
  
  int totalPageSize = getTotalPageSize();
  boolean isHead = false;
  boolean isTail = false;
  if (headTailDisable) {
   if (currentPageNo == 1) {
    isHead = true;
   } else if (currentPageNo == totalPageSize) {
    //如果页容量较大只有一页时,此时既是首页又是尾页如果两个都禁用可能导致用户无法点击分页所以故意写成else if形式
    isTail = true;
   }
  }
  //System.out.println("---- random = " + r);
  //FIXME:builder.append("<div style=\"float: left\">&nbsp;Total Data[<font color=\"red\">");
  builder.append("<div style=\"float: left\">&nbsp;总共<font color=\"red\">");
  builder.append(totalDataSize);
  builder.append("</font>条&nbsp;<font color=\"red\">");
  //builder.append("</font>]&nbsp;Total Page[<font color=\"red\">");
  builder.append(totalPageSize);
  builder.append("</font>页&nbsp;当前<font color=\"red\">");
  //FIXME: builder.append("</font>]&nbsp;Current No.[<font color=\"red\">");
  builder.append(currentPageNo);
  builder.append("</font>");
  builder.append("页&nbsp;&nbsp;");
  //builder.append("]&nbsp;&nbsp;");
  builder.append("当前:");
  builder.append(getFirstResult());
  builder.append("-");
  builder.append(getLastResult());
  builder.append("&nbsp;");
  builder.append("</div>");
  
  builder.append("<div style=\"float: right;\">");
  //控制页容量
  if(psiEnable) {
   builder.append("每页: <input type=\"text\" name=\"pageSize\" id=\"pageSize"+random+"\" ");
   if(notEmpty(inputClass)) {
    builder.append("class=\""+inputClass+"\" ");
   }
   builder.append("value=\"");
   builder.append(pageSize);
   builder.append("\" size=\"3\">条&nbsp;&nbsp;");
  }else {
   builder.append("<input type=\"hidden\" name=\"pageSize\" id=\"pageSize"+random+"\" value=\"");
   if(pageSize != null) {
    builder.append(pageSize);
   }else {
    builder.append(Constants.DEFAULT_PAGE_SIZE);
   }
   builder.append("\">");
  }
  if(pngEnable) {
   if(pnShowNum == null || pnShowNum < Constants.MIN_PN_SHOW_NUM) {
    pnShowNum = Constants.MIN_PN_SHOW_NUM;
   }
   int start = 1, end = 0;
   if (totalPageSize <= pnShowNum) {
    end = totalPageSize;
   } else {
    int half = pnShowNum / 2 + 1;
    if (currentPageNo > half) {
     start = currentPageNo - half + 1;
    }
    end = start + pnShowNum - 1;
    if (totalPageSize < end) {
     end = totalPageSize;
     start = end - pnShowNum + 1;
    }
   }
   for (int i = start; i <= end; i++) {
    builder.append("<a href=\"javascript:page("+random+","+i+");\">");
    if(i != currentPageNo) {
     builder.append("["+i+"]");
    }else {
     builder.append(i);
    }
    builder.append("</a>&nbsp;&nbsp;");
   }
  }
  //控制转到页码组件输出,并记录当前页码
  if(pniEnable){
   builder.append("TO Page:<input type=\"text\" name=\"pageNo\" id=\"pageNoInp"+random+"\" ");
   if(notEmpty(inputClass)) {
    builder.append("class=\""+inputClass+"\" ");
   }
   builder.append("value=\"");
   builder.append(currentPageNo);
   builder.append("\" size=\"3\">&nbsp;<input type=\"button\" value=\"跳转\" ");
   //FIXME: builder.append("\" size=\"3\">&nbsp;<input type=\"button\" value=\"Go\" ");
   if(notEmpty(btnClass)) {
    builder.append("class=\""+btnClass+"\" ");
   }
   builder.append("onclick=\"javascript:page("+random+",document.getElementById('pageNoInp"+random+"').value);\">&nbsp;&nbsp;&nbsp;");
  }
  // 控制页码选择组件的输出,并记录当前页码
  if(pnsEnable) {
   // id属性可以去掉
   builder.append("<select name=\"pageNo\" onchange=\"javascript:page("+random+",this.value)\" ");
   if(notEmpty(selClass)) {
    builder.append("class=\""+selClass+"\" ");
   }
   builder.append(">");
   for (int i = 1; i <= totalPageSize; i++) {
    builder.append("<option ");
    if(i == currentPageNo) {
     builder.append("selected ");
    }
    builder.append("value=\""+i+"\">"+i+"</option>");
   }
   builder.append("</select>&nbsp;&nbsp;");
  }
  if(!pniEnable && !pnsEnable) {
   builder.append("<input type=\"hidden\" name=\"pageNo\" value=\""+currentPageNo+"\">");
  }
  
  if (pnbEnable) {
   builder.append("<input type=\"button\" ");
   if(notEmpty(btnClass)) {
    builder.append("class=\""+btnClass+"\" ");
   }
   if (isHead) {
    builder.append("disabled=\"disabled\" ");
   }
   builder.append("value=\"首页\" onClick=\"javascript:page("+random+","+getTopPageNo()+");\">&nbsp;");
   builder.append("<input type=\"button\" ");
   if(notEmpty(btnClass)) {
    builder.append("class=\""+btnClass+"\" ");
   }
   if (isHead) {
    builder.append("disabled=\"disabled\" ");// FIXME:ff下不起作用
   }
   builder.append("value=\"上页\" onClick=\"javascript:page("+random+","+getPrevPageNo()+");\">&nbsp;");
   //builder.append("value=\"Prev\" onClick=\"javascript:page("+random+","+getPrevPageNo()+");\">&nbsp;");
   builder.append("<input type=\"button\" ");
   if(notEmpty(btnClass)) {
    builder.append("class=\""+btnClass+"\" ");
   }
   if (isTail) {
    builder.append("disabled=\"disabled\" ");
   }
   builder.append("value=\"下页\" onClick=\"javascript:page("+random+","+getNextPageNo()+");\">&nbsp;");
   //builder.append("value=\"Next\" onClick=\"javascript:page("+random+","+getNextPageNo()+");\">&nbsp;");
   builder.append("<input type=\"button\" ");
   if(notEmpty(btnClass)) {
    builder.append("class=\""+btnClass+"\" ");
   }
   if (isTail) {
    builder.append("disabled=\"disabled\" ");
   }
   builder.append("value=\"尾页\" onClick=\"javascript:page("+random+","+getLastPageNo()+");\">&nbsp;");
   //builder.append("value=\"Last\" onClick=\"javascript:page("+random+","+getLastPageNo()+");\">&nbsp;");
  }
  
  builder.append("</div>");
  builder.append("<script language=\"javascript\">function page(id, pageNo){var ps = document.getElementById('pageSize'+id);");
  builder.append("if(!isPositiveInt(ps.value)){alert('每页条数请输入大于0的数字');ps.focus();return;}");
  builder.append("if(!isPositiveInt(pageNo)){alert('页码请输入大于0的数字');document.getElementById('pageNoInp'+id).focus();return;}");
  builder.append("var psv = parseInt(ps.value);var tds = parseInt("+totalDataSize+");");
  builder.append("if((pageNo-1)*psv>=tds){pageNo=parseInt((tds+psv-1)/psv);}");
  builder.append("var pnArray = document.getElementsByName('pageNo');var psArray = document.getElementsByName('pageSize');");
  builder.append("for(i=0;i<pnArray.length;i++){pnArray[i].value=pageNo;}for(i=0;i<psArray.length;i++){psArray[i].value=psv;}");
  builder.append("document.getElementById('"+formId+"').submit();}");
  builder.append("function isPositiveInt(v){var validateExp = /^[1-9]+[0-9]*$/;if (validateExp.test(v)) return true;");
  builder.append("return false;}</script>");
  builder.append("<br>");
  

  /*
   * 2011-1-11 17:54:37 改为使用正则表达式校验
   * org_Id=1&user4Id=zs&5loginType=A1
   * Test=vb&&Date=1202&&&&Type=on&&
   * 变量的情况比较复杂,不做太严格的限制
   */
  if(StringUtil.validateParam(queryParams)) {
   //System.out.println("---- 查询参数校验通过:" + queryParams);
   String[] params = queryParams.split("&");
   for (int i = 0; i < params.length; i++) {
    String kvStr = params[i];
    if (StringUtil.notEmpty(kvStr)) {
     String[] kv = kvStr.split("=");
     builder.append("<input type=\"hidden\" name=\"" + kv[0] + "\" value=\"" + kv[1] + "\">");
    }
   }
  }
  
  JspWriter out = pageContext.getOut();
  try {
   out.write(builder.toString());
   return SKIP_BODY;
  } catch (IOException e) {
   e.printStackTrace();
   throw new JspException(e);
  }
 }
 
 
 private static boolean notEmpty(String str) {
  if (str != null && !"".equals(str.trim())) {
   return true;
  }
  return false;
 }
 
 public static void main(String[] args) {
  //String str = "abc=d&e=&&=v";
  //System.out.println(str.matches(".*=+.*$"));
  // a=b&c=&&=v&efg&hijk= >> a=b,c=,=v,,efg,hijk=,
  String[] params = "a=b&c=&&=v&efg&hijk=".split("&");
  for (int i = 0; i < params.length; i++) {
   String kvStr = params[i];
   //System.out.println(kvStr);
   if (kvStr.length() >= 3 && kvStr.indexOf("=") > -1) {
    String[] kv = kvStr.split("=");
    if(kv!= null && kv.length==2 && notEmpty(kv[0]) && notEmpty(kv[1])) {
     System.out.println(kv[0] + "=" + kv[1]);
    }
   }
  }
 }
}

 

 2.Page.java封装分页信息

package com.lenovo.quartz.foundation.module;

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

/**
 * Page.java
 *
 *
 * Description:
 *
 * Copyright: Copyright (c)2010 Company: iSoftStone
 *
 * @author: WeiShaoying
 * @version: 1.0
 * @Time: 2010-10-3 09:09:44
 *
 */

@SuppressWarnings("unchecked")
public class Page implements Serializable {

 private static final long serialVersionUID = 4662036686627540269L;

 // not use Generics
 private List datas;

 private Integer pageSize;

 private Integer currentPageNo;

 private Integer totalDataSize;

 public List getDatas() {
  return datas;
 }

 public void setDatas(List datas) {
  this.datas = datas;
 }

 public Integer getPageSize() {
  return pageSize;
 }

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

 public Integer getCurrentPageNo() {
  return currentPageNo;
 }

 public void setCurrentPageNo(Integer currentPageNo) {
  this.currentPageNo = currentPageNo;
 }

 public Integer getTotalDataSize() {
  return totalDataSize;
 }

 public void setTotalDataSize(Integer totalDataSize) {
  this.totalDataSize = totalDataSize;
 }
}

 

 3.Tag所需的Tld描述文件

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>

   <tlib-version>1.0</tlib-version>
   <jsp-version>2.0</jsp-version>
   <short-name>DS Taglib</short-name>
   <uri>http://www.ds.com/weishaoying/tags</uri>
   <display-name>DS Test Taglib</display-name>
   <description><![CDATA[DS JSP Taglib Write on 2010-10-04 by Weishaoying]]></description>
  
   <tag>
  <name>page</name>
  <tag-class>com.lenovo.quartz.foundation.tag.PageTag</tag-class>
  <body-content>empty</body-content>
  <description>write pagination info to the jsp page</description>
  <attribute>
   <name>totalDataSize</name>
   <required>true</required>
   <rtexprvalue>true</rtexprvalue>
   <description><![CDATA[total data number, must fill in]]></description>
  </attribute>
  <attribute>
   <name>currentPageNo</name>
   <required>true</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
   <name>pageSize</name>
   <required>true</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
   <name>formId</name>
   <required>true</required>
   <rtexprvalue>true</rtexprvalue>
   <description><![CDATA[must fill in]]></description>
  </attribute>
  <attribute>
   <name>btnClass</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
   <description><![CDATA[button css]]></description>
  </attribute>
  <attribute>
   <name>queryParams</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
   <name>headTailDisable</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
   <name>inputClass</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
   <name>selClass</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
   <name>psiEnable</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
   <name>pniEnable</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
   <name>pnsEnable</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
   <name>pnbEnable</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
   <name>pngEnable</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
   <name>pnShowNum</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
  </attribute>
   </tag>
  
</taglib>


4.BaseAction中对分页进行了一些处理,这样我们的业务逻辑Action集成BaseAction后,不用写相同的处理逻辑。

package com.lenovo.quartz.foundation.action;

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

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.lenovo.quartz.foundation.constant.Constants;
import com.lenovo.quartz.foundation.module.Page;
import com.lenovo.quartz.foundation.util.StringUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * BaseAction.java
 *
 * Description: This Action provide some common methods for struts action
 *
 * @Copyright: Copyright(c)2011 Weishaoying. All right reserved.
 * @author: WeiShaoying
 * @Mail: weishaoying-99@163.com
 * @version: 1.0
 * @date: 2011-11-28
 *
 */

public class BaseAction extends ActionSupport {

 private static final long serialVersionUID = -5047224046242607477L;

 protected static Logger logger = Logger.getLogger(BaseAction.class);

 // default page number = 1
 protected String pageNo;

 // how many datas per page
 protected String pageSize;

 // show page info
 protected String pageMsg;

 // show error info
 protected String errorMsg;

 // Page object, you can use it in it's sub class
 protected Page page;

 // spring use this method to set value for variable
 public void setPageNo(String pageNo) {
  this.pageNo = pageNo;
 }

 // this method is necessary
 public void setPageSize(String pageSize) {
  this.pageSize = pageSize;
 }

 public String getPageMsg() {
  return pageMsg;
 }

 public void setPageMsg(String pageMsg) {
  this.pageMsg = pageMsg;
 }

 public String getErrorMsg() {
  return errorMsg;
 }

 public void setErrorMsg(String errorMsg) {
  this.errorMsg = errorMsg;
 }

 public static Logger getLogger() {
  return logger;
 }

 public static void setLogger(Logger logger) {
  BaseAction.logger = logger;
 }

 // define some common used methods for get request, response, session
 protected ActionContext getActionContext() {
  return ActionContext.getContext();
 }

 // get request
 protected HttpServletRequest getRequest() {
  return ServletActionContext.getRequest();
 }

 // get response
 protected HttpServletResponse getResponse() {
  // return (HttpServletResponse)
  // getActionContext().get(ServletActionContext.HTTP_RESPONSE);
  return ServletActionContext.getResponse();
 }

 // get session
 protected HttpSession getSession() {
  return getRequest().getSession();
 }

 // get servletContext
 protected ServletContext getServletContext() {
  return (ServletContext) getActionContext().get(ServletActionContext.SERVLET_CONTEXT);
 }

 // unified handling
 public int getPageSize() {
  if (StringUtil.empty(pageSize)) {
   // give default page size
   return Constants.DEFAULT_PAGE_SIZE;
  } else if (pageSize.indexOf(",") > -1) {
   // struts2 transfer value for example : 5,5,5
   pageSize = pageSize.split(",")[0];
  }
  // the most commonly used
  return Integer.parseInt(pageSize);
 }

 // unfied handling
 public int getPageNo() {
  // when you did't pass pageNo, I'll give a default value
  if (StringUtil.empty(pageNo)) {
   return Constants.DEFAULT_PAGE_NO;
  } else if (pageNo.indexOf(",") > -1) {
   pageNo = pageNo.split(",")[0];
  }
  return Integer.parseInt(pageNo);
 }

 // very import ,necessary
 public Page getPage() {
  return page;
 }

 // not necessary
 public void setPage(Page page) {
  this.page = page;
 }

}

5.我们自己的业务逻辑Action,这里也CustomerAction为例

package com.lenovo.quartz.app.action;

import com.lenovo.quartz.app.service.ICustomerManagerService;
import com.lenovo.quartz.app.vo.CustomerVo;
import com.lenovo.quartz.foundation.action.BaseAction;
import com.lenovo.quartz.foundation.constant.Constants;

/**
 * CustomerVo.java
 *
 * Description:
 *
 * @Copyright: Copyright(c)2011 Weishaoying. All right reserved.
 * @author: WeiShaoying
 * @Mail: weishaoying-99@163.com
 * @version: 1.0
 * @date: 2011-11-29 10:25:27
 *
 */

public class CustomerAction extends BaseAction {

 private static final long serialVersionUID = 2789220958905922488L;

 private CustomerVo Customer;

 private ICustomerManagerService custService;

 /**
  * Effect:
  *
  * @author Weishaoying
  * @version 1.0
  * @return
  */
 public String queryCustomerWithPage() {
  // 分页的核心步骤
  page = custService.queryCustomerWithPage(null, this.getPageSize(), this.getPageNo());
  if (page != null) {
   return SUCCESS;
  }
  return Constants.ERROR;
 }

 public CustomerVo getCustomer() {
  return Customer;
 }

 public void setCustomer(CustomerVo customer) {
  Customer = customer;
 }

 public void setCustService(ICustomerManagerService custService) {
  this.custService = custService;
 }

}

 

6.service接口省略

7.service实现类CustomerManagerServiceImpl

package com.lenovo.quartz.app.service.impl;

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

import org.apache.log4j.Logger;

import com.lenovo.quartz.app.dao.ICustomerManagerDao;
import com.lenovo.quartz.app.module.Customer;
import com.lenovo.quartz.app.service.ICustomerManagerService;
import com.lenovo.quartz.app.vo.CustomerVo;
import com.lenovo.quartz.foundation.dao.IBaseDao;
import com.lenovo.quartz.foundation.exception.DaoException;
import com.lenovo.quartz.foundation.exception.JobException;
import com.lenovo.quartz.foundation.module.Page;
import com.lenovo.quartz.foundation.util.ContextService;
import com.lenovo.quartz.foundation.util.StringUtil;

/**
 * CustomerManagerServiceImpl.java
 *
 * Description:
 *
 * @Copyright: Copyright(c)2011 Weishaoying. All right reserved.
 * @author: WeiShaoying
 * @Mail: weishaoying-99@163.com
 * @version: 1.0
 * @date: 2011-11-29 10:21:59
 *
 */

public class CustomerManagerServiceImpl implements ICustomerManagerService, Serializable {

 private static final long serialVersionUID = -8383535667336701811L;

 private ContextService contextService;

 // 经验证@Transient方式is not ok
 // private Logger logger = Logger.getLogger(getClass());

 //private IBaseDao baseDao;
 
 // TODO: 如果当前service为job,则一定要如下方式获得
// public void setBaseDao(IBaseDao baseDao) {
//  this.baseDao = baseDao;
// }

 public void setContextService(ContextService contextService) {
  this.contextService = contextService;
 }

 @SuppressWarnings("unchecked")
 @Override
 public Page queryCustomerWithPage(CustomerVo Customer, Integer pageSize, Integer pageNo) throws JobException {
  String hql = " from Customer ";
  String totalNumHql = " select count(*) from Customer ";
  Page page = new Page();
  IBaseDao baseDao = contextService.getBean(IBaseDao.class, "baseDao");
  try {
   page.setDatas(baseDao.queryByHqlWithPage(hql, pageSize, pageNo));
   page.setPageSize(pageSize);
   page.setCurrentPageNo(pageNo);
   page.setTotalDataSize(baseDao.countByHqlWithParams(totalNumHql));
   return page;
  } catch (DaoException e) {
   Logger logger = Logger.getLogger(getClass());
   logger.error(e);
   throw new JobException(e.getCode(), e.getMessage(), e);
  }
 }

 @SuppressWarnings("unchecked")
 @Override
 public void createCust(int num) throws JobException {
  if (num <= 0) {
   return;
  }
  // get current max id
  String sql = " select max(id) from t_customer ";
  List ids;
  try {
   IBaseDao baseDao = contextService.getBean(IBaseDao.class, "baseDao");
   ids = baseDao.queryBySqlWithParams(sql); //when create you should do like this
   int maxId = 0;
   if (StringUtil.notEmpty(ids) && ids.get(0) != null) {
    maxId = (Integer) ids.get(0);
   }
   List<Customer> cs = new ArrayList<Customer>();
   for (int i = 0; i < num; i++) {
    Customer ct = new Customer();
    // new customer id beginwith id+1
    maxId++;
    ct.setId(maxId);
    ct.setName("Name_" + maxId);
    ct.setEmail("ct_" + maxId + "@163.com");
    ct.setAge(maxId);
    cs.add(ct);
   }
   baseDao.saveOrUpdateAll(cs);
  } catch (DaoException e) {
   Logger logger = Logger.getLogger(getClass());
   logger.error(e);
   throw new JobException(e.getCode(), e.getMessage(), e);
  }
 }

 @Override
 public void testMethod1() {
  ICustomerManagerDao customerDao = contextService.getBean(ICustomerManagerDao.class, "customerDao");
  Customer customer = customerDao.getCustomer();
  Logger logger = Logger.getLogger(getClass());
  logger.info(customer);
 }

 @Override
 public void testMethod2() {
  Logger logger = Logger.getLogger(getClass());
  ICustomerManagerDao customerDao = contextService.getBean(ICustomerManagerDao.class, "customerDao");
  Customer c = customerDao.updateCustAge();
  logger.info("---------> After update : " + c.toString());
 }
}

8.Dao接口省略

9.Dao实现类也省略,因为我的Service实现类中调用的是BaseDao,其实Dao的工作大致都差不多,我很烦每个模块都重复相同的代码,所以大部分的功能都写在BaseDao中,每个模块特有的功能才写在它对应的Dao中。

 

10.页面上如何使用Tag呢?

<%@ page language="java" contentType="text/html; charset=gbk"%>
<%@include file="/common/common.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>客户列表</title>
<link href="${path }/css/page.css" rel="stylesheet" type="text/css">
<link href="${path }/css/tab.css" rel="stylesheet" type="text/css">

</head>
<body>
<p><a href="${path }">返回首页</a></p>
<br>
<form name="form1" id="form1" action="queryCustomerWithPage.do" method="post">
<table class="warp_table" id="tbl" width="99%" align="center">
<!--
<table border="0" width="100%" cellspacing="0" cellpadding="0" class="tablepadding" id="lineItemTable">
 New:<s:property value='#page.pageSize'/>
 2OK:<s:property value='page.pageSize'/>
 3OK:<s:property value='%{page.pageSize}'/>
 -->
   <tr id="tr1">
    <td nowrap height="3" colspan="4">
      <ds:page
      pageSize="${page.pageSize}"
      totalDataSize="${page.totalDataSize}"
      currentPageNo="${page.currentPageNo}"
      formId="form1"
      btnClass="btn_2k3"
      pniEnable="true"
      pnsEnable="true"
      pngEnable="false"
      psiEnable="true"
      headTailDisable="true"
     />
     <%--
     
     --%>
    </td>
   </tr>
   <tr id="tr4">
    <td nowrap height="3" colspan="4">
     <ds:page
      pageSize="${page.pageSize}"
      totalDataSize="${page.totalDataSize}"
      currentPageNo="${page.currentPageNo}"
      formId="form1"
      btnClass="btn_2k3"
      pniEnable="false"
      pnbEnable="false"
      pnsEnable="true"
      pngEnable="false"
      psiEnable="false"
      headTailDisable="true"
     />
    </td>
   </tr>
   <tr id="tr5">
    <td nowrap height="3" colspan="4">
     <ds:page
      pageSize="${page.pageSize}"
      totalDataSize="${page.totalDataSize}"
      currentPageNo="${page.currentPageNo}"
      formId="form1"
      btnClass="btn_2k3"
      pniEnable="false"
      pnbEnable="true"
      pnsEnable="false"
      pngEnable="false"
      psiEnable="true"
      headTailDisable="false"
     />
    </td>
   </tr>
   <tr id="tr1" height="24" align="center" style="font-weight: bold;">
    <td align="center" itemId="a1" class="tableColumn">序号</td>
     <td align="center" itemId="a1" class="tableColumn">客户名称</td>
     <td align="center" itemId="a3" class="tableColumn">客户邮箱</td>
     <td align="center" itemId="a4" class="tableColumn">客户年龄</td>
   </tr> 
 <c:choose>
     <c:when test="${not empty page.datas}">
   <c:forEach items="${page.datas}" var="item" varStatus="status">
     <tr align="center">
      <td>${status.count }</td>
       <td>${item.name }</td>
       <td>${item.email }</td>
       <td>${item.age }</td>
     </tr>
   </c:forEach>
   
   <tr id="tr2">
    <td nowrap height="3" colspan="4">
     <ds:page
      pageSize="${page.pageSize}"
      totalDataSize="${page.totalDataSize}"
      currentPageNo="${page.currentPageNo}"
      formId="form1"
      btnClass="btn_2k3"
      psiEnable="true"
      pngEnable="true"
      pnbEnable="false"
      pnShowNum="21"
      headTailDisable="true"
     />
    </td>
   </tr>
   <tr id="tr3">
    <td nowrap height="3" colspan="4">
     <ds:page
      pageSize="${page.pageSize}"
      totalDataSize="${page.totalDataSize}"
      currentPageNo="${page.currentPageNo}"
      formId="form1"
      btnClass="btn_2k3"
      psiEnable="false"
      pngEnable="true"
      pnbEnable="true"
      pnShowNum="15"
      headTailDisable="true"
     />
    </td>
   </tr>
  </c:when>
        <c:otherwise>
   <tr><td colspan="4">没有查询到相应的数据!</td></tr>
  </c:otherwise>
     </c:choose>
</table>
</form>
<script src="${path }/js/common.js" type="text/javascript"></script>
</body>
</html>

 

 

 这是本人2010年国庆节期间写的分页框架,后经过不断完善,个人感觉功能非常灵活、强大,现与各位分享。

 

写的比较仓促,有时间了再加注释!

以后会逐渐奉上一些技术原创,敬请关注!

谢谢! 

 

 


下面附上实例图:

  • dao.rar (3.1 KB)
  • 下载次数: 13
  • 大小: 7.4 KB
  • 大小: 8.2 KB
  • 大小: 7.6 KB
  • 大小: 5.1 KB
  • 大小: 6.7 KB
  • 大小: 5.2 KB
  • 大小: 7.2 KB
  • 大小: 9.6 KB
  • 大小: 12 KB
  • 大小: 10.5 KB
  • 大小: 11.9 KB
分享到:
评论
1 楼 reshuibuleng 2012-09-13  
不知完整源码是否可以交流下 1131740977@qq.com 谢谢。

相关推荐

    史上最牛的java分页技术

    在本案例中,我们将探讨一种“史上最牛”的Java分页技术,它结合了SSH(Struts、Hibernate、Spring)框架和Ajax技术。 首先,我们要明确分页的基本概念。分页是将数据库中的大量数据分割成小块,每次只加载一部分到...

    史上最强大的php分页类

    本文将详细介绍“史上最强大的PHP分页类”,帮助开发者理解其原理、用法以及如何优化用户体验。 首先,PHP分页类通常包含以下几个核心功能: 1. 计算总页数:根据数据库查询结果中的记录总数和每页显示的记录数来...

    一个很简单的分页框架

    在IT行业中,分页是一种常见的数据展示技术,尤其在网页应用和数据库操作中,它能够有效地管理和呈现大量的数据,提高用户体验。"一个很简单的分页框架"标题所提及的,可能是一个轻量级的库或者组件,设计用于帮助...

    三大框架分页技术

    综上所述,掌握三大框架的分页技术对于Java Web开发至关重要。理解如何在Spring MVC、Struts2和Hibernate中优雅地实现分页,可以提升应用性能,优化用户体验,同时结合用户登录功能,确保数据的安全访问。在实践中,...

    自制纯js分页框架

    【自制纯js分页框架】是一个轻量级的JavaScript库,设计用于在Web应用程序中实现高效、简洁的分页功能。这个框架强调纯净和微型,意味着它不依赖任何外部库,如jQuery,使得它在现代Web开发环境中更具灵活性和可移植...

    java+pager-taglib分页框架

    Java分页框架是Java开发中常见的一种技术,用于在大量数据中实现高效的页面导航。Pager-taglib是一个基于JSP标签库的分页解决方案,它提供了一种简单且灵活的方式来在Web应用中展示分页信息。这个框架使得开发者可以...

    android 分页加载框架

    在Android开发中,分页加载框架是用于处理大数据集时的一种高效、用户友好的解决方案。它允许应用程序在用户滚动时动态加载数据,从而减少内存消耗,提高应用性能,并提供流畅的用户体验。本篇文章将深入探讨分页...

    目前最好的JSP分页技术

    总结来说,JSP分页技术的选择和实现取决于多种因素,开发者应根据项目需求灵活运用各种方法,以达到最佳的效果。无论采用何种方式,都要注重代码的可读性、可维护性和性能优化,确保分页功能的稳定和高效。

    ssh框架分页案例,简单易懂

    这个分页案例提供了使用SSH框架实现数据分页的功能,旨在帮助开发者更好地理解和应用这一技术。以下是对SSH框架分页案例的详细解读: 1. **Struts2**:作为MVC(Model-View-Controller)框架,Struts2负责处理HTTP...

    ssh框架实现的分页代码

    综上所述,这个项目旨在展示SSH框架下如何实现数据库分页功能,涉及到的主要技术有Spring的依赖管理和事务控制、Struts2的请求处理和视图展示、Hibernate的对象关系映射以及Oracle数据库的查询操作。开发者可以通过...

    基于ssm框架下的分页显示查询

    基于ssm框架进行分页查询。数据库mysql、前端Easy_UI框架。在大量数据的查询下,我们需要使用到分页查询。对应博客请查看:基于ssm框架下的分页显示

    JS分页框架

    JavaScript 分页框架是一种用于在网页上展示大量数据时进行数据分块显示的技术,它能够有效提高用户体验,避免一次性加载过多内容导致页面响应速度变慢。在这个项目中,我们使用了AngularJS和Bootstrap这两个流行的...

    基于SSM框架下的分页系统案例

    这个基于SSM框架的分页系统案例,旨在教你如何在实际项目中实现高效、灵活的分页功能,提升用户体验。下面将详细阐述SSM框架的核心组件以及在分页系统中的应用。 首先,Spring作为核心的依赖注入(DI)和面向切面...

Global site tag (gtag.js) - Google Analytics