欢迎大家来到爱尚实训技术分享课堂,相信大家平时在做WEB程序时经常会用到分页的功能。但是实现分页功能时,操作相对比较麻烦,如果能够封装一个分页工具类,那样讲大量提升开发的效率,因此,今天给大家分享一个分页类的小实例,希望能够对大家有所帮助。
一、数据库准备
1)编写Mysql数据库脚本,代码如下:
drop table if exists news;
create table news
(
newsId int auto_increment primary key not null,
title varchar(200) unique not null,
author varchar(50) not null,
publishDate date not null,
content varchar(2000)
);
2)添加24条测试数据,方便分页测试:
二、实体类编写
1)编写实体类,代码如下:
public class News {
private int newsId;
private String title;
private String author;
private String publishDate;
private String content;
//set方法,get方法省略
}
三、数据库基本访问类
1)编写读取配置文件类,代码如下:
public class CommonProperties extends Properties {
private static CommonProperties instance = null;
private CommonProperties() {
InputStream is = getClass().getResourceAsStream("/basic.properties");
try {
super.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized static CommonProperties getInstance() {
if (instance == null)
instance = new CommonProperties();
return instance;
}
}
2)以JDBC为例,编写数据库基本访问类,代码如下:
public class BaseDao {
protected final String DRIVER=CommonProperties.getInstance().getProperty(“driver”);
protected final String URL=CommonProperties.getInstance().getProperty(“url”);
protected final String USERNAME=CommonProperties.getInstance().getProperty(“username”);
protected final String PASSWORD=CommonProperties.getInstance().getProperty(“password”);
protected Connection connection;
protected PreparedStatement preparedStatement;
protected ResultSet resultSet;
public void getConnection()throws Exception{
Class.forName(DRIVER);
this.connection=DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
public void executeQuery(String sql,Object… args)throws Exception{
this.getConnection();
this.preparedStatement=this.connection.prepareStatement(sql);
if(args!=null) {
for (int i = 0; i < args.length; i++) {
this.preparedStatement.setObject(i+1, args[i]);
}
}
this.resultSet=this.preparedStatement.executeQuery();
System.out.println(sql);
}
public void close()throws Exception{
if(this.resultSet!=null) this.resultSet.close();
if(this.preparedStatement!=null)this.preparedStatement.close();
if(this.connection!=null)this.connection.close();
}
}
四、数据访问层接口及实现类
1)编写数据访问接口,代码如下:
public interface NewsDao {
/**
* 根据条件分页查询新闻列表
* @param condition 条件判断对象
* @param page 页码
*/
public List select(News condition,int page)throws Exception;
/**
* 根据条件查询新闻数量
* @param condition 判断条件对象
*/
public int size(News condition) throws Exception;
}
2)编写数据访问实现类,代码如下:
public class NewsDaoImpl extends BaseDao implements NewsDao {
@Override
public List select(News condition, int page) throws Exception {
StringBuffer sql = new StringBuffer("select * from news where 1=1 ");
Map<String, Object> maps = this.getSqlAndArgs(sql, condition);
return this.iterater(
maps.get(“sql”).toString() + " limit " + (page - 1) * Common.PAGE_SIZE + “,” + Common.PAGE_SIZE,(Object[]) maps.get(“args”));
}
@Override
public int size(News condition) throws Exception {
StringBuffer sql = new StringBuffer("select count(*) from news where 1=1 ");
Map<String, Object> maps = this.getSqlAndArgs(sql, condition);
Object obj = super.uniqueValue(maps.get(“sql”).toString(), (Object[])
maps.get(“args”));
return obj != null ? Integer.parseInt(obj.toString()) : 0;
}
/**
* 根据条件获取SQL语句及相应的参数列表
* @param sql SQL语句
* @param condition 判断条件对象
/
private Map<String, Object> getSqlAndArgs(StringBuffer sql, News condition) {
List args = new ArrayList();
if (condition != null) {
//动态查询语句拼接部分省略
}
Map<String, Object> maps = new HashMap<String, Object>();
maps.put(“sql”, sql.toString());
maps.put(“args”, args.toArray(new Object[] {}));
return maps;
}
/*
* 遍历结果集方法
* @param sql SQL语句
* @param args 参数列表
/
private List iterater(String sql, Object… args) throws Exception {
try {
List objs = new ArrayList();
super.executeQuery(sql, args);
while (super.resultSet.next()) {
News obj = new News();
obj.setNewsId(super.resultSet.getInt(1));
obj.setTitle(super.resultSet.getString(2));
obj.setAuthor(super.resultSet.getString(3));
obj.setPublishDate(super.resultSet.getString(4));
obj.setContent(super.resultSet.getString(5));
objs.add(obj);
}
return objs;
} finally {
super.close();
}
}
}
五、编写分页类,代码如下:
/*
- 分页类
/
public class Pager {
public Pager(List objs, int page, int count) {
this.objs = objs;
this.page = page;
this.count = count;
this.cal();
}
public static final int PAGE_SIZE=Integer.parseInt(CommonProperties.getInstance().getProperty(“page_size”));
/*- 当页显示内容
/
private List objs;
/* - 总记录数
/
private int count;
/* - 当前页码
/
private int page;
/* - 总页数
/
private int pages;
/* - 首页
/
private int first;
/* - 末页
/
private int last;
/* - 上一页
/
private int pre;
/* - 下一页
/
private int next;
/* - 计算页码方法
/
private void cal() {
this.pages = this.count % PAGE_SIZE == 0 ? this.count / PAGE_SIZE
: this.count / PAGE_SIZE + 1;
this.first = 1;
this.last = this.pages;
if (this.page > 1)
this.pre = this.page - 1;
else
this.pre = 1;
if (this.pages > this.page)
this.next = this.page + 1;
else
this.next = this.pages;
}
/* - 获取分页的页码列表,默认显示10个页码
*/
public List getPageList() {
List pageList = new ArrayList();
int start=1;
if(this.page-4>=1)
start = this.page - 4;
if(start+9>this.pages)
start-=start+9-this.pages;
for (int i = 0; i < 10; i++) {
pageList.add(start);
if (start <= this.pages)
start++;
}
return pageList;
}
}
六、业务接口及实现类
1)编写业务接口,代码如下:
public interface NewsService {
public Pager get(News conditon,int page);
}
2)编写业务实现类,代码如下:
public class NewsServiceImpl implements NewsService {
private NewsDao newsDao=new NewsDaoImpl();
@Override
public Pager get(News conditon, int page) {
pager pager=null;
try {
List newses=this.newsDao.select(condition, page);
int count=this.newsDao.size(condition);
pager=new Pager<>(newses, page, count);
}catch (Exception e) {
e.printStackTrace();
}
return pager;
}
}
七、效果测试,为了节约时间,这里直接用控制台测试:
@Test
public void test() {
NewsService service=new NewsServiceImpl();
Pager pager = service.get(null, 1);
System.out.println(“新闻编号\t新闻标题\t新闻作者\t”);
for (News obj : pager.getObjs()) {
System.out.println(obj.getNewsId() + “\t” + obj.getTitle()+"\t"+obj.getAuthor());
}
String pageList="";
for (Integer p : pager.getPageList()) {
pageList+=p+" “;
}
System.out.println(”\n当前:第" + pager.getPage() + “页 共” + pager.getPages()
- 当页显示内容
-
“页 a: 首页 b:上一页 “+pageList+” c:下一页 d:末页 系统中符合条件的记录有” + pager.getCount()
+ “条!”);
}
测试结果:更改当前页码为第六页,测试结果:
感谢大家的支持,希望能给大家带来帮助,爱尚实训Java技术分享课堂不定期会给大家带来更多的内容,请持续关注,下回再见!