【Bootstrap】Bootstrap和Java分页-第二篇
目录
- 关于此文
- 配置xml-pager.tld
- 分页控件-Pager
- 分页action集成类-BaseController
- 实例-Dao
- 实例-service
- 实例-action
- 实例-JSP
- 实例-SQL
- 实例图
关于此文
运用第一篇分页的例子,结果以失败告终。在网上又寻找了很多例子。大多是都是这一种。着手开发的项目采用spring MVC框架。符合需求。摘下来,试了一试。
网上的例子总是少一些东西。经过一番折腾。终于搞定了。下面分享出来,供参考。
分页基本逻辑思想懂了,重点是在于怎么实现。怎么实现更好。还需要进一步思考。
配置xml-pager.tld
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>Pager</description>
<tlib-version>1.0</tlib-version>
<short-name>page</short-name>
<uri></uri>
<tag>
<name>createPager</name>
<tag-class>getui.util.Pager</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>curPage</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.Integer</type>
</attribute>
<attribute>
<name>totalPage</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>
<attribute>
<name>totalCount</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.Integer</type>
</attribute>
<attribute>
<name>formId</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
</tag>
</taglib>
分页控件-Pager
package getui.util;
import java.io.IOException; import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport; /***
* 分页控件
*
* @author Anny
*/
public class Pager extends TagSupport { private Integer curPage; //当前页码
private Integer totalPage; //总页数
private Integer pageSize = 10; //一页显示的记录数
private Integer totalCount = 0; //记录总数
private String formId; //请求的action name
private Integer lastIndex; //结束索引 public int doStartTag() throws JspException {
StringBuffer buffer=new StringBuffer();
JspWriter out = pageContext.getOut(); int pageNumber = 0;
if (totalPage % pageSize == 0) {
pageNumber = totalPage / pageSize;
} else {
pageNumber = (totalPage / pageSize) + 1;
}
if (curPage < 1) {
curPage = 1;
} try {
if (pageNumber > 0) {
buffer.append("<script type='text/javascript'>");//script-Start
buffer.append("function go(pageNum)");
buffer.append("{");//{start
buffer.append("var f = document.getElementById('" + formId + "');");
buffer.append("f.action = f.action + '?pageNum=' + pageNum + '&pageSize="+pageSize + "';");
buffer.append("f.submit();" );
buffer.append("}");//}end
buffer.append("</script>");//script-end out.print(buffer.toString()); out.append("<div class='page-number-strip' style='height:62px;text-align: right;'> ");//page-number-strip
out.print("<ul class='pagination'>");//添加Bootstrap分页的样式pagination
int start = 1;
int end = totalPage;
for (int i = 4; i >= 1; i--) {
if ((curPage - i) >= 1) {
start = curPage - i;
break;
}
}
for (int i = 4; i >= 1; i--) {
if ((curPage + i) <= totalPage) {
end = curPage + i;
break;
}
}
// 如果小于9则右侧补齐
if (end - start + 1 <= 9) {
Integer padLen = 9 - (end - start + 1);
for (int i = padLen; i >= 1; i--) {
if ((end + i) <= totalPage) {
end = end + i;
break;
}
}
} // 如果还小于9左侧补齐
if (end - start + 1 <= 9) {
Integer padLen = 9 - (end - start + 1);
for (int i = padLen; i >= 1; i--) {
if ((start - i) >= 1) {
start = start - i;
break;
}
}
} if (curPage > 1) {
if (start > 1) {
out.print("<li><a href='javascript:go(1)'>首页</a></li>");
}
out.print("<li><a href='javascript:go(" + (curPage - 1) + ")'>上一页</a></li>");
} for (int i = start; i <= end; i++) {
if (i == curPage) {
out.print("<li class='active'><a href='javascript:void(0);'>" + i + "</a></li>");
} else {
out.print("<li><a href='javascript:go(" + i + ")'>" + i + "</a></li>");
}
}
if (curPage < totalPage) {
out.print("<li><a href='javascript:go(" + (curPage + 1) + ")'>下一页</a></li>");
if (end < totalPage) {
out.print("<li><a href='javascript:go(" + totalPage + ")'>尾页</a></li>");
}
}
out.print("<li><a href='javascript:void(0)'>共" + totalPage + "页" + this.totalCount + "条</a></li>");
out.print("</ul>");
out.print("</div>");
} } catch (IOException e) {
e.printStackTrace();
} return super.doStartTag(); } /**
* 算开始索引
*
* @param pageNum -
* @param pageSize
* @return
*/
public static Integer getStartIndex(Integer pageNum, Integer pageSize) {
Integer res = 0;
if (pageNum > 0) {
res = (pageNum - 1) * pageSize;
}
return res;
} /**
* 算结束索引 -- 方法暂时未用
*
* @param pageSize
* @param totalCount
* @param totalPage
* @param pageNum
* @return
*/
public static Integer getLastIndex(Integer pageSize,Integer totalCount,Integer totalPage,Integer pageNum){
//计算结束时候的索引
Integer lastIndex =0;
if( totalCount < pageSize){
lastIndex = totalCount;
}else if((totalCount % pageSize == 0) || (totalCount % pageSize != 0 && pageNum < totalPage)){
lastIndex = pageNum * pageSize;
}else if(totalCount % pageSize != 0 && pageNum == totalPage){//最后一页
lastIndex = totalCount ;
}
return lastIndex;
} public Integer getLastIndex() {
return lastIndex;
} public void setLastIndex(Integer lastIndex) {
this.lastIndex = lastIndex;
} public void setCurPage(Integer curPage) {
this.curPage = curPage;
} public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
} public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
} public void setFormId(String formId) {
this.formId = formId;
} public Integer getTotalCount() {
return totalCount;
} public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
} }
分页action集成类-BaseController
package getui.controller; import getui.util.Pager; import java.util.Iterator;
import java.util.List;
import java.util.Map; import org.springframework.ui.Model; /**
* 分页控件初始化父类
*
* @author Anny
*/
public class BaseController { //初始化分页相关信息
protected void initPage(Map<String,Object> map, Integer pageNum, Integer pageSize, Integer totalCount){
if(null==pageSize || pageSize.equals("")){
pageSize = 10; //每页显示条数
}
// if(pageSize>50){
// pageSize = 50;
// }
Integer totalPage = (totalCount+pageSize-1)/pageSize;
if(null==pageNum){
pageNum = 1;
}else if(pageNum>totalPage){
pageNum = totalPage;
}
map.put("startIndex", Pager.getStartIndex(pageNum, pageSize));
map.put("pageNum", pageNum);
map.put("totalPage", totalPage);
map.put("pageSize", pageSize);
map.put("totalCount", totalCount);
map.put("lastIndex", Pager.getLastIndex(pageSize,totalCount,totalPage,pageNum));
} //将相关数据放入model
protected void initResult(Model model, List<Map<String, Object>> list, Map<String,Object> map){
model.addAttribute("list", list);
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry m = (Map.Entry)it.next();
model.addAttribute(m.getKey().toString(), m.getValue());
}
} }
实例-Dao
package getui.dao; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository; import getui.controller.GeTuiController;
import getui.entity.Branch;
import getui.entity.GetuiInfo; @Repository("bookDao")
public class BookDao extends BaseDao{ /** 日志记录 .*/
private static Logger logger = Logger.getLogger(BookDao.class); public int getListCount(){
String sql ="select count(1) from Book";
return super.jdbcTemplate.queryForInt(sql);
} public List getListBook(int pageIndex,int pageSize){
String sql = "select * from Book where 1=1 limit "+pageIndex+","+pageSize; // String sql = "select a.*"
// + " from ("
// +" select id as nid,name ,price"
// +" from book"
// +" order by(id) "
// +" ) a"
// +" where nid between "+pageIndex+" and "+pageSize+"";
return super.jdbcTemplate.queryForList(sql);
} }
实例-service
package getui.service; import getui.dao.BookDao;
import getui.dao.ClientInfoDao;
import getui.entity.Branch;
import getui.entity.GetuiInfo; import java.util.List;
import java.util.Map; import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service("bookService")
public class BookService { /** 日志记录 .*/
private static Logger logger = Logger.getLogger(BookService.class); @Autowired
private BookDao bookDao; public int getListCount(){
return bookDao.getListCount();
} public List getListBook(int pageIndex,int pageSize){
return bookDao.getListBook(pageIndex, pageSize);
// return bookDao.getListBook();
}
}
实例-action
package getui.controller; import getui.service.BookService; import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; @Controller
@RequestMapping(value = "/test")
public class TestController extends BaseController { /** 日志记录 .*/
private static Logger logger = Logger.getLogger(TestController.class); @Autowired
private BookService bookService; @RequestMapping("/test.do")
public String test(Model model,String type, @RequestParam(required=false) Integer pageNum,
@RequestParam(required=false) Integer pageSize) { Map<String,Object> map = new HashMap<String,Object>();
map.put("type", type);
Integer totalCount = bookService.getListCount(); this.initPage(map, pageNum, pageSize, totalCount);
List list = this.bookService.getListBook(Integer.valueOf(String.valueOf(map.get("startIndex"))),
Integer.valueOf(String.valueOf(map.get("pageSize"))));
this.initResult(model, list, map); return "book";
} }
实例-JSP
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="page" uri="/WEB-INF/pager.tld"%>
<% String path = request.getContextPath(); %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>测试分页标签</title>
<link href="<%=path%>/css/bootstrap.css" rel="stylesheet">
<link href="<%=path%>/css/bootstrap-responsive.css" rel="stylesheet">
<script type="text/javascript">
function toDel(id){
var url = "<%=path%>/test/del?id=" + id +"&pageNum=${param.pageNum}&pageSize=${param.pageSize}";
window.location.href = url;
}
</script>
</head>
<body> <div class="container">
<c:forEach items="${list}" var="item">
<div class="border-bottom1">
<h3><a href="<%=path%>/test/view?id=${item.id}">${item.name}</a></h3>
<p>
${item.content}
</p>
<p class="text-right muted">
2013-06-22 22:37
<a href="javascript:toDel('${item.id}');">删除</a>
<a href="<%=path%>/test/toEdit?id=${item.id}&pageNum=${param.pageNum}&pageSize=${param.pageSize}">编辑</a>
</p>
</div>
</c:forEach>
<form method="post" id="testForm" action="<%=path%>/test/test.do">
<input type="hidden" name="type" value="${type}">
</form>
<page:createPager pageSize="${pageSize}" totalPage="${totalPage}" totalCount="${totalCount}" curPage="${pageNum}" formId="testForm"/>
</div> </body>
</html>
实例-SQL
/*
Navicat MySQL Data Transfer Source Server : 本地库
Source Server Version : 50621
Source Host : localhost:3306
Source Database : test Target Server Type : MYSQL
Target Server Version : 50621
File Encoding : 65001 Date: 2016-01-13 12:37:11
*/ SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `book`
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`price` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES ('', '图书1', '');
INSERT INTO `book` VALUES ('', '图书2', '');
INSERT INTO `book` VALUES ('', '图书3', '');
INSERT INTO `book` VALUES ('', '图书4', '');
INSERT INTO `book` VALUES ('', '图书5', '');
INSERT INTO `book` VALUES ('', '图书6', '');
INSERT INTO `book` VALUES ('', '图书7', '');
INSERT INTO `book` VALUES ('', '图书8', '');
INSERT INTO `book` VALUES ('', '图书9', '');
INSERT INTO `book` VALUES ('', '图书10', '');
INSERT INTO `book` VALUES ('', '图书11', '');
INSERT INTO `book` VALUES ('', '图书12', '');
INSERT INTO `book` VALUES ('', '图书13', '');
INSERT INTO `book` VALUES ('', '图书14', '');
INSERT INTO `book` VALUES ('', '图书15', '');
INSERT INTO `book` VALUES ('', '图书16', '');
INSERT INTO `book` VALUES ('', '图书17', '');
INSERT INTO `book` VALUES ('', '图书18', '');
INSERT INTO `book` VALUES ('', '图书19', '');
INSERT INTO `book` VALUES ('', '图书20', '');
INSERT INTO `book` VALUES ('', '图书21', '');
INSERT INTO `book` VALUES ('', '图书22', '');
INSERT INTO `book` VALUES ('', '图书23', '');
INSERT INTO `book` VALUES ('', '图书24', '');
实例图
测试示例图
分页融合到自己的代码中示例图
【Bootstrap】Bootstrap和Java分页-第二篇的更多相关文章
- Java SE 第二篇
二. Java SE 第二篇 1. Arrays 数组 // 声明一维数组,[]内不允许有值 int[] arr; int arr[]; // 创建一维数组对象,[]内必须有值 arr = new ...
- 8成以上的java线程状态图都画错了,看看这个-图解java并发第二篇
本文作为图解java并发编程的第二篇,前一篇访问地址如下所示: 图解进程线程.互斥锁与信号量-看完还不懂你来打我 图形说明 在开始想写这篇文章之前,我去网上搜索了很多关于线程状态转换的图,我惊讶的发现 ...
- 从.Net到Java学习第二篇——IDEA and start spring boot
从.Net到Java学习第一篇——开篇 所谓工欲善其事,必先利其器,做java开发也一样,在比较了目前最流行的几个java IDE(eclipse,myeclipse.IDEA)之后,我果断选择IDE ...
- 【Bootstrap】Bootstrap和Java分页-第一篇
目录 关于此文 pagination BetweenIndex DefaultPagination QueryHandler BookDaoImpl BookServiceImpl BookActio ...
- Java高新技术第二篇:反射技术
今天我们来看一下Java中的反射技术: 首先来了解一下Java中的反射的一些概念: Java中的反射是1.2引入的 反射的基石:class类 Class类的各个实例对象分别对应各个类在内存中的字节码, ...
- Java 学习 第二篇;面向对象 定义类的简单语法:
1:基本知识 [public / protected / private] class 类名 { 零个到多个构造器定义; 零个到多个属性; 零个到多个方法; } 其中类中各个成员之间的顺序没有关系,且 ...
- java分页通用篇
一.创建分页通用类 package com.dkyw.util; import java.util.List; public class Page<T> { private int tot ...
- 聊聊、Java 命令 第二篇
第一篇类之间没有依赖关系,所以比较简单,这一篇来看看有依赖的类怎么编译和执行. (一)Java 运行 class 有依赖 Person 是一个接口,只有一个 getName 方法.Man 则实现了 P ...
- java基础第二篇
3.选择结构 a.if: 格式一: if(表达式1){ 表达式1为真才执行 } 格式二: if(表达式1){ 表达式1为真才执行 }else{ 表达式1位假才执行 } 格式三:判断工龄的范围,判断成绩 ...
随机推荐
- 一、swoole安装
说明:swoole扩展需要安装php环境,这里就不说了. 1.有了PHP环境后,即可安装swoole扩展. swoole扩展下载地址:https://github.com/swoole/swoole- ...
- [NOIP2014] 提高组 洛谷P1941 飞扬的小鸟
题目描述 Flappy Bird 是一款风靡一时的休闲手机游戏.玩家需要不断控制点击手机屏幕的频率来调节小鸟的飞行高度,让小鸟顺利通过画面右方的管道缝隙.如果小鸟一不小心撞到了水管或者掉在地上的话,便 ...
- C#变量类型
在C#语言中,我们把变量分为七种类型,它们分别是:静态变量(static varibles),非静态变量(instance variables),数组元素(array elements),值参数(va ...
- Scala Trait
Scala Trait 大多数的时候,Scala中的trait有点类似于Java中的interface.正如同java中的class可以implement多个interface,scala中的cals ...
- CF 204B Little Elephant and Cards
题目链接: 传送门 Little Elephant and Cards time limit per test:2 second memory limit per test:256 megab ...
- POJ - Til the Cows Come Home(Dijkstra)
题意: 有N个点,给出从a点到b点的距离,当然a和b是互相可以抵达的,问从1到n的最短距离 分析: 典型的模板题,但是一定要注意有重边,因此需要对输入数据加以判断,保存较短的边,这样才能正确使用模板. ...
- javascript 未来新方法的介绍
JavaScript1.6数组方法的扩展 var tmp = [1, 2, 3, 4, 5, 3]; console.log('indexOf:找出数组中某一对象的下标,如果没有则为-1'); con ...
- ionic的scroll的使用出现的问题
今天再写ionic的时候发现了一个问题,在使用ui-view的时候引用ion-scroll指令的时候初次加载的时候能能实现拖拽滚动,只能实现滚动鼠标滚轴滚动,然后各种调试,各种比较,终于发现原来是路由 ...
- JavaScript 、jQuery动态创建元素的关键字~
JavaScript动态创建元素: 1.创建元素 如:a 标签 var alink= document.createElement("a"); 2.j添加元素属性 alink.h ...
- Java数据结构——有序链表
//================================================= // File Name : SortedList_demo //--------------- ...