首先,先扯下为何要用Velocity实现分页。因为最近在开发一个新闻发布的项目,需求很简单,能发布新闻。但是有个要求,需要将页面静态化。那这样说来,其实就是在夜深人静的时刻,模版化一堆的静态化新闻页面,然后用户每次就点进去浏览就可以了,大大减少和服务器的交互。听起来好像是很牛逼啊。
然后,静态化页面不难,可以看到我之前写的一遍文章,可以通过Velocity模版功能马上静态化出一张或者多张页面。但是问题出现了,如果出现分页那应该如何处理?是否还是需要通过动态来获取列表数据?其实不然,在考虑了一番之后,其实可以这样做,比如有100条数据,每页十条,那就把数据分割到10个页面里面,然后每张页面后面都有ID标识,在URL中加入标识,然后通过URL来互相访问静态页面,听起来好像还不错。反正先做,有问题再说呗。
然后再来谈谈具体如何实现:
1、新建java工程,加入velocity包,配置文档,vm文件,这个就不再继续展开来说
其中SRC中是具体实现的代码,在lib中是所需要用到的jar包,properties中是velocity用到的配置文件,在view中就是实现静态化的模版VM文件
2、新建实现分页的java类
主要实现分页功能的代码
package com.page.impl;
import java.util.ArrayList;
import java.util.List;
import com.page.Paginate;
//, com.bj58.wf.training.advert.code.sql.page.Paginate
public class DefaultPaginate implements Paginate{
protected long count;
protected int last;
protected int size;
protected long begin;
protected long end;
protected int previous;
protected int index;
protected int next;
protected boolean hasFirst;
protected boolean hasLast;
protected boolean hasNext;
protected boolean hasPrevious;
protected List<Integer> pages;
public DefaultPaginate() {
}
public void init(long count, int size, int index) {
this.count = count;
this.size = size;
this.index = index < 1 ? 1 : index;
this.begin = this.size * (this.index - 1);
this.end = this.size;
if (count % size > 0)
last = (int) (count / size + 1);
else
last = (int) (count / size);
hasNext = hasLast = index < last;
if (hasNext)
next = index + 1;
hasPrevious = hasFirst = index > 1;
if (hasPrevious)
previous = index - 1;
pages = new ArrayList<Integer>();
int start = 0;
int stop = 0;
if (index <= 5) {
sta