PagedListHolder 这个类可以 对分页操作进行封装

文件在:import org.springframework.beans.support.PagedListHolder;下

默认是把查出来的所有信息,根据设置的每页多少条显示,然后分割成若干个List集合,并显示出来。如果是小规模的分页,此方法用起来还是非常方便的。

如果是大规模的分页数据,那就非常影响效率。

演示DEMO:

package test;

import java.util.Iterator;
import java.util.List;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import entity.News;
import biz.NewsBiz; public class Test123 {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "context-ioc.xml" });
NewsBiz news = (NewsBiz) context.getBean("newsBiz");
List list = news.findAll();
PagedListHolder pagedList = new PagedListHolder(list);
// 设置每页显示的数量
pagedList.setPageSize(5);
int i = 1;
while (true) {
Iterator it = pagedList.getPageList().iterator();
System.out.println("第" + i + "页");
// 显示每页的内容
while (it.hasNext()) {
System.out.println(((News) it.next()).getNtitle());
}
// 如果是末页,则退出
if (pagedList.isLastPage()) {
break;
}
// 跳转到下一页
pagedList.nextPage();
i++; }
} }

在SPRING中:

	//全部新闻
public ModelAndView all(HttpServletRequest request,HttpServletResponse response){ newsList = newsBiz.findAll();
if (newsList!=null && !newsList.isEmpty()) {
//mv.addObject("newsList", newsList);
PagedListHolder<News> newsPageList = new PagedListHolder<News>(newsList);
   //设置每页显示的数量5
newsPageList.setPageSize(5);
List<News> newsList = newsPageList.getPageList();
mv.addObject("newsList", newsList);
}else {
mv.addObject("newsMsg", "暂无任何新闻!");
}
mv.setViewName("/WEB-INF/news/all.jsp");
return mv;
}

 在JSP中:

<c:forEach items="${newsList}" var="nlist" varStatus="vs">
<tr>
<td>${nlist.sort.stname}</td>
<td><a href="news.do?method=info&nid=${nlist.nid}" target="_blank">${nlist.ntitle}</a></td>
<td><fmt:formatDate value="${nlist.ntime}" pattern="yyyy/MM/dd HH:mm"/></td></tr>
<tr>
</c:forEach>

PagedListHolder.java源码:

/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.beans.support; import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; import org.springframework.util.Assert; /**
* PagedListHolder is a simple state holder for handling lists of objects,
* separating them into pages. Page numbering starts with 0.
*
* <p>This is mainly targetted at usage in web UIs. Typically, an instance will be
* instantiated with a list of beans, put into the session, and exported as model.
* The properties can all be set/get programmatically, but the most common way will
* be data binding, i.e. populating the bean from request parameters. The getters
* will mainly be used by the view.
*
* <p>Supports sorting the underlying list via a {@link SortDefinition} implementation,
* available as property "sort". By default, a {@link MutableSortDefinition} instance
* will be used, toggling the ascending value on setting the same property again.
*
* <p>The data binding names have to be called "pageSize" and "sort.ascending",
* as expected by BeanWrapper. Note that the names and the nesting syntax match
* the respective JSTL EL expressions, like "myModelAttr.pageSize" and
* "myModelAttr.sort.ascending".
*
* @author Juergen Hoeller
* @since 19.05.2003
* @see #getPageList()
* @see org.springframework.beans.support.MutableSortDefinition
*/
@SuppressWarnings("serial")
public class PagedListHolder<E> implements Serializable { public static final int DEFAULT_PAGE_SIZE = 10; public static final int DEFAULT_MAX_LINKED_PAGES = 10; private List<E> source; private Date refreshDate; private SortDefinition sort; private SortDefinition sortUsed; private int pageSize = DEFAULT_PAGE_SIZE; private int page = 0; private boolean newPageSet; private int maxLinkedPages = DEFAULT_MAX_LINKED_PAGES; /**
* Create a new holder instance.
* You'll need to set a source list to be able to use the holder.
* @see #setSource
*/
public PagedListHolder() {
this(new ArrayList<E>(0));
} /**
* Create a new holder instance with the given source list, starting with
* a default sort definition (with "toggleAscendingOnProperty" activated).
* @param source the source List
* @see MutableSortDefinition#setToggleAscendingOnProperty
*/
public PagedListHolder(List<E> source) {
this(source, new MutableSortDefinition(true));
} /**
* Create a new holder instance with the given source list.
* @param source the source List
* @param sort the SortDefinition to start with
*/
public PagedListHolder(List<E> source, SortDefinition sort) {
setSource(source);
setSort(sort);
} /**
* Set the source list for this holder.
*/
public void setSource(List<E> source) {
Assert.notNull(source, "Source List must not be null");
this.source = source;
this.refreshDate = new Date();
this.sortUsed = null;
} /**
* Return the source list for this holder.
*/
public List<E> getSource() {
return this.source;
} /**
* Return the last time the list has been fetched from the source provider.
*/
public Date getRefreshDate() {
return this.refreshDate;
} /**
* Set the sort definition for this holder.
* Typically an instance of MutableSortDefinition.
* @see org.springframework.beans.support.MutableSortDefinition
*/
public void setSort(SortDefinition sort) {
this.sort = sort;
} /**
* Return the sort definition for this holder.
*/
public SortDefinition getSort() {
return this.sort;
} /**
* Set the current page size.
* Resets the current page number if changed.
* <p>Default value is 10.
*/
public void setPageSize(int pageSize) {
if (pageSize != this.pageSize) {
this.pageSize = pageSize;
if (!this.newPageSet) {
this.page = 0;
}
}
} /**
* Return the current page size.
*/
public int getPageSize() {
return this.pageSize;
} /**
* Set the current page number.
* Page numbering starts with 0.
*/
public void setPage(int page) {
this.page = page;
this.newPageSet = true;
} /**
* Return the current page number.
* Page numbering starts with 0.
*/
public int getPage() {
this.newPageSet = false;
if (this.page >= getPageCount()) {
this.page = getPageCount() - 1;
}
return this.page;
} /**
* Set the maximum number of page links to a few pages around the current one.
*/
public void setMaxLinkedPages(int maxLinkedPages) {
this.maxLinkedPages = maxLinkedPages;
} /**
* Return the maximum number of page links to a few pages around the current one.
*/
public int getMaxLinkedPages() {
return this.maxLinkedPages;
} /**
* Return the number of pages for the current source list.
*/
public int getPageCount() {
float nrOfPages = (float) getNrOfElements() / getPageSize();
return (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
} /**
* Return if the current page is the first one.
*/
public boolean isFirstPage() {
return getPage() == 0;
} /**
* Return if the current page is the last one.
*/
public boolean isLastPage() {
return getPage() == getPageCount() -1;
} /**
* Switch to previous page.
* Will stay on first page if already on first page.
*/
public void previousPage() {
if (!isFirstPage()) {
this.page--;
}
} /**
* Switch to next page.
* Will stay on last page if already on last page.
*/
public void nextPage() {
if (!isLastPage()) {
this.page++;
}
} /**
* Return the total number of elements in the source list.
*/
public int getNrOfElements() {
return getSource().size();
} /**
* Return the element index of the first element on the current page.
* Element numbering starts with 0.
*/
public int getFirstElementOnPage() {
return (getPageSize() * getPage());
} /**
* Return the element index of the last element on the current page.
* Element numbering starts with 0.
*/
public int getLastElementOnPage() {
int endIndex = getPageSize() * (getPage() + 1);
int size = getNrOfElements();
return (endIndex > size ? size : endIndex) - 1;
} /**
* Return a sub-list representing the current page.
*/
public List<E> getPageList() {
return getSource().subList(getFirstElementOnPage(), getLastElementOnPage() + 1);
} /**
* Return the first page to which create a link around the current page.
*/
public int getFirstLinkedPage() {
return Math.max(0, getPage() - (getMaxLinkedPages() / 2));
} /**
* Return the last page to which create a link around the current page.
*/
public int getLastLinkedPage() {
return Math.min(getFirstLinkedPage() + getMaxLinkedPages() - 1, getPageCount() - 1);
} /**
* Resort the list if necessary, i.e. if the current {@code sort} instance
* isn't equal to the backed-up {@code sortUsed} instance.
* <p>Calls {@code doSort} to trigger actual sorting.
* @see #doSort
*/
public void resort() {
SortDefinition sort = getSort();
if (sort != null && !sort.equals(this.sortUsed)) {
this.sortUsed = copySortDefinition(sort);
doSort(getSource(), sort);
setPage(0);
}
} /**
* Create a deep copy of the given sort definition,
* for use as state holder to compare a modified sort definition against.
* <p>Default implementation creates a MutableSortDefinition instance.
* Can be overridden in subclasses, in particular in case of custom
* extensions to the SortDefinition interface. Is allowed to return
* null, which means that no sort state will be held, triggering
* actual sorting for each {@code resort} call.
* @param sort the current SortDefinition object
* @return a deep copy of the SortDefinition object
* @see MutableSortDefinition#MutableSortDefinition(SortDefinition)
*/
protected SortDefinition copySortDefinition(SortDefinition sort) {
return new MutableSortDefinition(sort);
} /**
* Actually perform sorting of the given source list, according to
* the given sort definition.
* <p>The default implementation uses Spring's PropertyComparator.
* Can be overridden in subclasses.
* @see PropertyComparator#sort(java.util.List, SortDefinition)
*/
protected void doSort(List<E> source, SortDefinition sort) {
PropertyComparator.sort(source, sort);
} }

  

关于Spring中的PagedListHolder分页类的分析的更多相关文章

  1. Spring中的@Transactional 放在 类级别 和 方法级别 上有什么不同?

    Spring中的@Transactional 放在类级别 和 方法级别 上有什么不同? @Transactional放在类级别上是否等同于该类的每个方法都放上了@Transactional? 是的一般 ...

  2. Spring中的JDBC模板类入门

    1.Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单 2.提供了JDBC模板,Spring框架提供的 *JdbcTemplate类 3.Spring框架可以整合Hib ...

  3. python---django中自带分页类使用

    请先看在学习tornado时,写的自定义分页类:思路一致: python---自定义分页类 1.基础使用: 后台数据获取: from django.core.paginator import Pagi ...

  4. Yii2中自带分页类实现分页

    1.首先写控制器层 先引用pagination类 use yii\data\Pagination; 写自己的方法: function actionFenye(){        $data = Fie ...

  5. php中的实用分页类

    <table width="100%" border="1" cellpadding="0" cellspacing="0& ...

  6. spring中的数据库操作类

    例子一: package cn.itcast.service.impl; import java.util.List; import javax.sql.DataSource; import org. ...

  7. spring中bean配置和注入场景分析

    bean与spring容器的关系 Bean配置信息定义了Bean的实现及依赖关系,Spring容器根据各种形式的Bean配置信息在容器内部建立Bean定义注册表,然后根据注册表加载.实例化Bean,并 ...

  8. spring中排除某个类

    在spring中可能需要排除某个类,做法是在spring配置文件中加入如下配置 <context:component-scan base-package="com.ias" ...

  9. CI框架分页类

    分页类1.分页类参数说明 'base_url' => 指向你的分页所在的控制器类/方法的完整的 URL, 'total_rows' => 数据的总行数, 'per_page' => ...

随机推荐

  1. 如何避免被C++默认拷贝构造函数忽悠?

    一.背景介绍           因为工作关系,需要用到C++编程.对于我来说,虽然一直从事的是linux平台下的嵌入式软件开发,但深入用到C++的特性的地方并不多.对于C++,用得最多的无非是指针. ...

  2. Vim 自动文件头注释与模板定义

    Vim 自动文件头注释与模板定义 在vim的配置文件.vimrc添加一些配置可以实现创建新文件时自动添加文件头注释,输入特定命令可以生成模板. 使用方法 插入模式输入模式输入seqlogic[Ente ...

  3. mysql 的密码重置

    Windows: 1.以系统管理员登陆: 2.停止MySQL服务: 3.进入CMD,进入MySQL的安装目录,假设是D:/MySQL/MySQL Server 5.0/: 4.跳过权限检查启动MySQ ...

  4. LayoutInflater 原理分析 示例

    LayoutInflater简介        LayoutInflater 顾名思义就是布局填充器,做过Android界面编程,相信对这个类都比较熟悉,可能有人说,我们在activity中使用set ...

  5. java 位运算权限管控(转载)

    这里笔者介绍一种很常用,也比较专业的权限控制思路.这里用java语言描述,其实都差不多的.要换成其他的语言主,自己转一下就可以了.为了方便起见,我们这里定义a^b为:a的b次方.这里,我们为每一个操作 ...

  6. Segment对象

    Segment对象是一个有起点和终点的“线“,也就是说Segement只有两个点,至于两点之间的线是直的,还是曲的,需要其余的参数定义. 所以Segment是由起点,终点和参数三个方面决定的.Segm ...

  7. 验证码 Demo

    //设置响应头 response.setCharacterEncoding("image/jpeg"); int width=160; int height=40; Buffere ...

  8. django TypeError: 'module' object is not callable

    原因:导入模块时直接把模块当函数使用 from rest_framework import reverse #import reverse module @api_view(("GET&qu ...

  9. 作业:汽车查询--弹窗显示详情,批量删除 ajax做法(0521)

    作业:显示以下界面: 作业要求: 1.查看详细信息,以弹窗的形式显示,使用ajax2.批量删除 一.主页面 <!DOCTYPE html PUBLIC "-//W3C//DTD XHT ...

  10. 利用csc.exe 手动编译C#程序

    1. 创建见 cs代码文件 using System; class TestApp{ static void Main() { Console.WriteLine("Test! 1,2,3& ...