Struts2+Hibernate+Spring分頁自定義標籤
分頁問題一直是專案中不可避免的問題,之前由於一直忙著做專案,裡面的分頁覺得做的不是很完善,很多的程式碼需要複製粘帖,特別是在jsp頁面上顯示的時候,所以花了幾天時間好好完善下!
1、封裝分頁資訊的bean
- package com.beckham.page;
- import java.util.List;
- /**
- * @author beckham
- * Jul 30, 2009 4:13:43 PM
- * 分頁資訊
- */
- public class PageBean {
- private int totalSize; // 記錄總條數
- private int pageSize; // 每頁顯示條數
- private int prePage; // 上一頁
- private int nextPage; // 下一頁
- private int currPage; // 當前頁
- private int lastPage; // 最後頁
- private int pageCount; // 總頁數
- private int beginIndex ;
- private int endIndex ;
- public int getBeginIndex() {
- return beginIndex;
- }
- public void setBeginIndex(int beginIndex) {
- this.beginIndex = beginIndex;
- }
- public int getEndIndex() {
- return endIndex;
- }
- public void setEndIndex(int endIndex) {
- this.endIndex = endIndex;
- }
- public int getTotalSize() {
- return totalSize;
- }
- public void setTotalSize(int totalSize) {
- this.totalSize = totalSize;
- }
- public int getPageSize() {
- return pageSize;
- }
- public void setPageSize(int pageSize) {
- this.pageSize = pageSize;
- }
- public int getPrePage() {
- return prePage;
- }
- public void setPrePage(int prePage) {
- this.prePage = prePage;
- }
- public int getNextPage() {
- return nextPage;
- }
- public void setNextPage(int nextPage) {
- this.nextPage = nextPage;
- }
- public int getCurrPage() {
- return currPage;
- }
- public void setCurrPage(int currPage) {
- this.currPage = currPage;
- }
- public int getLastPage() {
- return lastPage;
- }
- public void setLastPage(int lastPage) {
- this.lastPage = lastPage;
- }
- public int getPageCount() {
- return pageCount;
- }
- public void setPageCount(int pageCount) {
- this.pageCount = pageCount;
- }
- }
2、通過 傳遞的引數來計算分頁資訊,引數主要有 當前頁(currPage)、結果集的總條數(totalSize)、每頁顯示的數量(pageSize),我把pageSize寫在了配置檔案裡面,這樣可以靈活的修改配置。
- package com.beckham.page;
- import com.beckham.util.PropertyUtil;
- public class PageMessage {
- /*
- * (non-Javadoc)
- * 獲取分頁資訊
- * @see com.beckham.page.PageMessageInterface#getPageMessage(int,
- * java.lang.String)
- */
- public static PageBean getPageMessage(int currPage, int totalSize)
- throws Exception {
- PageBean pagebean = new PageBean();
- int pageSize = PropertyUtil.getPageSize();
- int pageCount = 0;
- int prePage = 0;
- int nextPage = 0;
- int begindex;
- int endindex;
- // 總頁數
- if (totalSize % pageSize == 0) { // 判斷是否整除
- pageCount = (int) totalSize / pageSize;
- } else {
- pageCount = (int) totalSize / pageSize + 1;
- }
- if (currPage > 1) {
- prePage = currPage – 1; // 上一頁
- } else {
- prePage = 1;
- }
- if (currPage < pageCount) {
- nextPage = currPage + 1; // 下一頁
- } else {
- nextPage = currPage;
- }
- //開始索引
- if (currPage > pageCount) {
- begindex = (pageCount – 1) * pageSize;
- } else {
- begindex = (currPage – 1) * pageSize;
- }
- //結束索引
- if(currPage*pageSize>totalSize){
- endindex = totalSize ;
- }else{
- endindex=currPage*pageSize ;
- }
- pagebean.setPrePage(prePage);
- pagebean.setPageSize(pageSize);
- pagebean.setCurrPage(currPage);
- pagebean.setTotalSize(totalSize);
- pagebean.setPageCount(pageCount);
- pagebean.setLastPage(pageCount);
- pagebean.setNextPage(nextPage);
- pagebean.setBeginIndex(begindex) ;
- pagebean.setEndIndex(endindex) ;
- return pagebean;
- }
- }
3、由此就可以在action裡面呼叫了。
- package com.beckham.struts.actions;
- import java.util.List;
- import java.util.Map;
- import org.apache.struts2.interceptor.RequestAware;
- import com.beckham.model.User;
- import com.beckham.page.PageBean;
- import com.beckham.page.PageMessage;
- import com.beckham.service.UserService;
- import com.opensymphony.xwork2.ActionSupport;
- @SuppressWarnings(“serial”)
- public class UserListAction extends ActionSupport implements RequestAware {
- private UserService userService;
- private int currPage;
- @SuppressWarnings(“unchecked”)
- private Map request;
- private String path;
- private String password ;
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getPath() {
- return path;
- }
- public void setPath(String path) {
- this.path = path;
- }
- @SuppressWarnings( { “unchecked”, “unchecked” })
- public String execute() throws Exception {
- //查詢結果集總數
- String hqlSize = “select count(*) from User”;
- //查詢目標結果集
- String hql = “from User”;
- if (currPage == 0) {
- currPage = 1;
- }
- //獲取分頁資訊
- PageBean pageBean = PageMessage.getPageMessage(currPage, userService.gettotalSize(hqlSize));
- /*
- *
- *獲取結果集,這裡是和hibernate結合使用,所以引數需要傳一個beginIndex
- * pageSize寫在配置檔案裡面,所以這裡就不用當做引數傳遞了
- */
- List<User> list = userService.queryUser(hql, pageBean.getBeginIndex());
- StringBuffer sb = new StringBuffer();
- //帶有引數的URL
- sb.append(“userlist.action?password=”).append(password).append(“&”) ;
- path = sb.toString();
- request.put(“users”, list);
- request.put(“path”, path) ;
- request.put(“pageBean”, pageBean);
- return SUCCESS;
- }
- public UserService getUserService() {
- return userService;
- }
- public void setUserService(UserService userService) {
- this.userService = userService;
- }
- @SuppressWarnings(“unchecked”)
- public void setRequest(Map request) {
- this.request = request;
- }
- @SuppressWarnings(“unchecked”)
- public Map getRequest() {
- return request;
- }
- public int getCurrPage() {
- return currPage;
- }
- public void setCurrPage(int currPage) {
- this.currPage = currPage;
- }
- }
當然在呼叫的時候需要呼叫service裡面的2個方法 gettotalSize(hqlSize) 和queryUser(hql, pageBean.getBeginIndex())
這2個方法的作用是獲取結果集的總記錄數和 獲取本次查詢的結果集,具體實現如下:
- public int gettotalSize(String hql) throws Exception {
- int totalsize = 0;
- try {
- totalsize = Integer.parseInt(this.getHibernateTemplate().find(hql)
- .get(0).toString());
- } catch (Exception e) {
- e.printStackTrace();
- throw new Exception(“查詢使用者總數失敗”, e);
- }
- return totalsize;
- }
- public List<User> queryUser(String hql, int beginIndex) throws Exception {
- try {
- return (List<User>) this.getHibernateTemplate().getSessionFactory()
- .getCurrentSession().createQuery(hql).setFirstResult(
- beginIndex).setMaxResults(
- PropertyUtil.getPageSize()).list();
- } catch (Exception e) {
- e.printStackTrace();
- throw new Exception(“查詢使用者出現異常”, e);
- }
- }
實現裡面的PropertyUtil.getPageSize() 方法是從配置檔案裡面讀取pageSize
- pageSize=5
- downloadPath=img/
- pageNumber=10
PropertyUtil.java
- package com.beckham.util;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Properties;
- public class PropertyUtil {
- private static Properties p = new Properties() ;
- private static InputStream inputStream = null ;
- static {
- inputStream = PropertyUtil.class.getResourceAsStream(“/page.properties”) ;
- try {
- p.load(inputStream) ;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static int getPageSize(){
- return Integer.parseInt(p.getProperty(“pageSize”));
- }
- public static int getPageNumber(){
- return Integer.parseInt(p.getProperty(“pageNumber”));
- }
- public static String getDownloadPath(){
- return p.getProperty(“downloadPath”);
- }
- public static void main(String[] args) {
- System.out.println(getPageSize());
- }
- }
到此,分頁的邏輯已經算是完成了,主要實現是利用了hibernateTemplate來實現查詢,所以在查詢的時候其實只需要setFirstResult ,setMaxResults就可以,也就是從什麼地方開始取,每次最多取多少條記錄!
接下來就是寫標籤了
- package com.tag;
- import java.io.IOException;
- import javax.servlet.jsp.JspException;
- import javax.servlet.jsp.JspWriter;
- import javax.servlet.jsp.tagext.SimpleTagSupport;
- import com.beckham.util.PropertyUtil;
- /**
- * @author beckham 分頁標籤 Oct 22, 2009 9:20:49 PM
- */
- public class PageTag extends SimpleTagSupport {
- private String path; // 請求路徑
- private String param; // 傳遞引數
- private int currPage; // 當前頁
- private int totalPage;// 總頁數
- private int totalSize;
- private int pageCount;
- private int pageSize;
- public int getTotalSize() {
- return totalSize;
- }
- public void setTotalSize(int totalSize) {
- this.totalSize = totalSize;
- }
- 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 getPath() {
- return path;
- }
- public void setPath(String path) {
- this.path = path;
- }
- public String getParam() {
- return param;
- }
- public void setParam(String param) {
- this.param = param;
- }
- public int getCurrPage() {
- return currPage;
- }
- public void setCurrPage(int currPage) {
- this.currPage = currPage;
- }
- public int getTotalPage() {
- return totalPage;
- }
- public void setTotalPage(int totalPage) {
- this.totalPage = totalPage;
- }
- public void doTag() throws JspException, IOException {
- JspWriter out = this.getJspContext().getOut();
- StringBuffer sb = new StringBuffer();
- sb.append(“<mce:style type=/”text/css/”><!–
- “) ;
- sb.append(“* { margin:0; padding:0;}”) ;
- sb.append(“body { font-size:13px; font-family:Verdana;width:100%;}”) ;
- sb.append(“a { color:#333; text-decoration:none;}”) ;
- sb.append(“a:hover {text-decoration:none;color:#FF0000;font-weight:bold;}”);
- sb.append(“ul { list-style:none;}”) ;
- sb.append(“#pagelist {width:100%; margin:30px auto; padding:6px 0px; height:20px;}”) ;
- sb.append(“#pagelist ul li { float:left; border:1px solid #5d9cdf; height:20px; line-height:20px; margin:0px 2px;}”) ;
- sb.append(“#pagelist ul li a, .pageinfo { display:block; padding:0px 6px; background:#e6f2fe;}”) ;
- sb.append(“.current { background:#a9d2ff; display:block; padding:0px 6px; font-weight:bold;}”) ;
- sb.append(”
- –></mce:style><style type=/“text/css/” mce_bogus=“1”>”) ;
- sb.append(“* { margin:0; padding:0;}”) ;
- sb.append(“body { font-size:13px; font-family:Verdana;width:100%;}”) ;
- sb.append(“a { color:#333; text-decoration:none;}”) ;
- sb.append(“a:hover {text-decoration:none;color:#FF0000;font-weight:bold;}”);
- sb.append(“ul { list-style:none;}”) ;
- sb.append(“#pagelist {width:100%; margin:30px auto; padding:6px 0px; height:20px;}”) ;
- sb.append(“#pagelist ul li { float:left; border:1px solid #5d9cdf; height:20px; line-height:20px; margin:0px 2px;}”) ;
- sb.append(“#pagelist ul li a, .pageinfo { display:block; padding:0px 6px; background:#e6f2fe;}”) ;
- sb.append(“.current { background:#a9d2ff; display:block; padding:0px 6px; font-weight:bold;}”) ;
- sb.append(“</style>”) ;
- sb.append(“<div id=/”pagelist/“>”);
- sb.append(“<ul>”) ;
- if (currPage == 1) {
- sb.append(“<li>”) ;
- sb.append(“首頁”);
- sb.append(“</li>”) ;
- sb.append(“<li>”) ;
- sb.append(“上一頁”);
- sb.append(“</li>”) ;
- } else {
- sb.append(“<li>”) ;
- sb.append(“<a href=”/” mce_href=”/“”“);
- sb.append(path);
- sb.append(param);
- sb.append(“=1”);
- sb.append(“/”“);
- sb.append(“>”);
- sb.append(“首頁”);
- sb.append(“</a>”);
- sb.append(“</li>”) ;
- sb.append(“<li>”) ;
- sb.append(“<a href=”/” mce_href=”/“”“);
- sb.append(path);
- sb.append(param);
- sb.append(“=”);
- sb.append(currPage – 1);
- sb.append(“/”“);
- sb.append(“>”);
- sb.append(“上一頁”);
- sb.append(“</a>”);
- sb.append(“</li>”) ;
- }
- // 顯示頁碼 預設顯示pageNumber個頁碼
- int pageNumber = PropertyUtil.getPageNumber();
- // 總頁數小於需要顯示的頁碼數
- int result = (currPage-1) / pageNumber;
- int begin = 1;
- int end = 1;
- begin = result * pageNumber+1;
- end = (result + 1) * pageNumber;
- if (end >= totalPage) {
- end = totalPage;
- }
- for (int i = begin; i <currPage; i++) {
- sb.append(“<li>”).append(“<a href=”/” mce_href=”/“”“).append(path).append(param).append(“=”)
- .append(i).append(“/”“).append(“></a>”).append(i).append(
- “</a>”).append(“</li>”);
- }
- sb.append(“<li class=/”current/“>”).append(currPage).append(“</li>”);
- for (int i = currPage+1; i <=end; i++) {
- sb.append(“<li>”).append(“<a href=”/” mce_href=”/“”“).append(path).append(param).append(“=”)
- .append(i).append(“/”“).append(“></a>”).append(i).append(
- “</a>”).append(“</li>”);
- }
- if (currPage == totalPage) {
- sb.append(“<li>”) ;
- sb.append(“下一頁”);
- sb.append(“</li>”) ;
- sb.append(“<li>”) ;
- sb.append(“末頁”);
- sb.append(“</li>”) ;
- } else {
- sb.append(“<li>”) ;
- sb.append(“<a href=”/” mce_href=”/“”“);
- sb.append(path);
- sb.append(param);
- sb.append(“=”);
- sb.append(currPage + 1);
- sb.append(“/”“);
- sb.append(“>”);
- sb.append(“下一頁”);
- sb.append(“</a>”);
- sb.append(“</li>”) ;
- sb.append(“<li>”) ;
- sb.append(“<a href=”/” mce_href=”/“”“);
- sb.append(path);
- sb.append(param);
- sb.append(“=”);
- sb.append(totalPage);
- sb.append(“/”“);
- sb.append(“>”);
- sb.append(“末頁”);
- sb.append(“</a>”);
- sb.append(“</li>”) ;
- }
- sb.append(“<li>”) ;
- sb.append(” “);
- sb.append(“總共”);
- sb.append(“<font color=/”red/“>”);
- sb.append(totalSize);
- sb.append(“</font>”);
- sb.append(“條結果”);
- sb.append(” “);
- sb.append(” “);
- sb.append(“當前”);
- sb.append(“<font color=/”red/“>”);
- sb.append(currPage);
- sb.append(“</font>”);
- sb.append(“/”);
- sb.append(“<font color=/”red/“>”);
- sb.append(pageCount);
- sb.append(“頁”) ;
- sb.append(“</font>”);
- sb.append(“</li>”) ;
- sb.append(” “);
- sb.append(“</ul>”) ;
- sb.append(“</div>”);
- out.println(sb);
- }
- }
標籤寫完,當然就是寫tld檔案了
- <?xml version=“1.0” encoding=“UTF-8” ?>
- <taglib xmlns=“http://java.sun.com/xml/ns/javaee”
- xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
- xsi:schemaLocation=“http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd”
- version=“2.1”>
- <tlib-version>1.1</tlib-version>
- <short-name>pageTag</short-name>
- <uri>/WEB-INF/pagetag.tld</uri>
- <tag>
- <name>pageInfo</name>
- <tag-class>com.tag.PageTag</tag-class>
- <body-content>empty</body-content>
- <attribute>
- <name>path</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- <attribute>
- <name>currPage</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- <type>java.lang.Integer</type>
- </attribute>
- <attribute>
- <name>param</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- </attribute>
- <attribute>
- <name>totalPage</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- <type>java.lang.Integer</type>
- </attribute>
- <attribute>
- <name>totalSize</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- <type>java.lang.Integer</type>
- </attribute>
- <attribute>
- <name>pageCount</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- <type>java.lang.Integer</type>
- </attribute>
- <attribute>
- <name>pageSize</name>
- <required>true</required>
- <rtexprvalue>true</rtexprvalue>
- <type>java.lang.Integer</type>
- </attribute>
- </tag>
- </taglib>
最後的一步就是在頁面上顯示查詢結果和用標籤顯示分頁資訊
- <%@ page language=“java” import=“java.util.*” pageEncoding=“UTF-8”%>
- <%@ taglib uri=“/struts-tags” prefix=“s”%>
- <%@ taglib uri=“/WEB-INF/pagetag.tld” prefix=“pt”%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + “://”
- + request.getServerName() + “:” + request.getServerPort()
- + path + “/”;
- %>
- <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
- <html>
- <head>
- <base href=“<%=basePath%>”>
- <title>My JSP `mess.jsp` starting page</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”>
- </head>
- <body>
- <div>
- <table border=“1” style=“width: 100%” align=“center”>
- <tr>
- <td>
- id
- </td>
- <td>
- 使用者名稱
- </td>
- <td>
- 姓名
- </td>
- <td>
- 年齡
- </td>
- <td>
- 性別
- </td>
- <s:iterator id=“user” value=“#request.users”>
- <tr>
- <td>
- <s:property value=“#user.id” />
- </td>
- <td>
- <s:property value=“#user.username” />
- </td>
- <td>
- <s:property value=“#user.realname” />
- </td>
- <td>
- <s:property value=“#user.age” />
- </td>
- <td>
- <s:property value=“#user.sex” />
- </td>
- </tr>
- </s:iterator>
- </tr>
- <tr>
- </table>
- </div>
- <div style=“width: 100%”>
- <pt:pageInfo pageCount=“${pageBean.pageCount }”
- currPage=“${pageBean.currPage }”
- param=“currPage”
- path=“${path}”
- totalPage=“${pageBean.lastPage }”
- pageSize=“${pageBean.pageSize }”
- totalSize=“${pageBean.totalSize }”
- />
- </div>
- </body>
- </html>
顯示效果由於圖片無法上傳,所以也就貼不上來了!
相關文章
- spring 自定義標籤Spring
- 自定義標籤FlowTagLayout
- JSP 自定義標籤介紹JS
- 自定義分頁格式
- 擴充spring元件之自定義標籤Spring元件
- JSP自定義標籤就是如此簡單JS
- [外掛擴充套件]onethink自定義分類標籤-關聯模型套件模型
- 聊聊自定義SPI如何使用自定義標籤注入到spring容器中Spring
- python 自定義資料分頁Python
- Django自定義模板標籤與過濾器Django過濾器
- 實戰練習之Jsp自定義標籤JS
- ssycms常用分類列表頁面的呼叫標籤
- spring原始碼深度解析— IOC 之 自定義標籤解析Spring原始碼
- Django5關於 自定義過濾器和標籤Django過濾器
- 使用 Laravel Resource 類時自定義分頁資訊Laravel
- Android自定義View實現流式佈局(熱門標籤效果)AndroidView
- 死磕Spring之IoC篇 - 解析自定義標籤(XML 檔案)SpringXML
- 怎樣向自定義標籤裡傳遞用Controller裡的assign()傳遞到頁面上的值Controller
- HTML簡介,結構,標籤以及標籤語義HTML
- html標籤分類HTML
- elementplus中標籤頁操作
- 這一次搞懂Spring自定義標籤以及註解解析原理Spring
- JUnit5學習之五:標籤(Tag)和自定義註解
- Prometheus自定義指標Prometheus指標
- 易優arclist 文件列表(配合arcpagelist標籤可實現ajax瀑布流分頁)-Eyoucms標籤手冊
- macOS Monterey 12 新功能介紹 – Safari標籤頁分組功能Mac
- Laravel 中 dingo API tranformer 返回自定義分頁格式資料LaravelGoAPIORM
- XAF自定義啟動頁
- 標籤評分:海量標籤如何進行系統治理?
- CSS自定義滑鼠指標CSS指標
- SAP UI5 列表控制元件分頁顯示資料時,如何自定義分頁大小UI控制元件
- Spring 原始碼(4)在Spring配置檔案中自定義標籤如何實現?Spring原始碼
- Mybatis原始碼分析(七)自定義快取、分頁的實現MyBatis原始碼快取
- 小程式標籤頁切換效果
- vue元件之路之Tabs標籤頁Vue元件
- Html網頁標籤曝光埋點HTML網頁
- HTML5 之語義標籤HTML
- 如何自定義Safari的起始頁
- 自定義OAM錯誤頁面