Bootstrap和Java分页实例第二篇


Posted in Javascript onDecember 23, 2016

关于此文

运用第一篇分页的例子,结果以失败告终。在网上又寻找了很多例子。大多是都是这一种。着手开发的项目采用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', '图书1', '10');
INSERT INTO `book` VALUES ('2', '图书2', '11');
INSERT INTO `book` VALUES ('3', '图书3', '12');
INSERT INTO `book` VALUES ('4', '图书4', '13');
INSERT INTO `book` VALUES ('5', '图书5', '14');
INSERT INTO `book` VALUES ('6', '图书6', '15');
INSERT INTO `book` VALUES ('7', '图书7', '16');
INSERT INTO `book` VALUES ('8', '图书8', '17');
INSERT INTO `book` VALUES ('9', '图书9', '18');
INSERT INTO `book` VALUES ('10', '图书10', '19');
INSERT INTO `book` VALUES ('11', '图书11', '11');
INSERT INTO `book` VALUES ('12', '图书12', '23');
INSERT INTO `book` VALUES ('13', '图书13', '22');
INSERT INTO `book` VALUES ('14', '图书14', '22');
INSERT INTO `book` VALUES ('15', '图书15', '22');
INSERT INTO `book` VALUES ('16', '图书16', '9');
INSERT INTO `book` VALUES ('17', '图书17', '10');
INSERT INTO `book` VALUES ('18', '图书18', '2');
INSERT INTO `book` VALUES ('19', '图书19', '8');
INSERT INTO `book` VALUES ('20', '图书20', '78');
INSERT INTO `book` VALUES ('21', '图书21', '21');
INSERT INTO `book` VALUES ('22', '图书22', '22');
INSERT INTO `book` VALUES ('23', '图书23', '23');
INSERT INTO `book` VALUES ('24', '图书24', '24');

实例图

测试示例图

Bootstrap和Java分页实例第二篇

分页融合到自己的代码中示例图

Bootstrap和Java分页实例第二篇

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
javascript实用小函数使用介绍
Nov 11 Javascript
javascript框架设计读书笔记之数组的扩展与修复
Dec 02 Javascript
JavaScript内存管理介绍
Mar 13 Javascript
jQuery实现垂直半透明手风琴特效代码分享
Aug 21 Javascript
前端面试题及答案整理(二)
Aug 26 Javascript
javascript 通过键名获取键盘的keyCode方法
Dec 31 Javascript
angularJs提交文本框数据到后台的方法
Oct 08 Javascript
微信小程序如何调用新闻接口实现列表循环
Jul 02 Javascript
深入理解令牌认证机制(token)
Aug 22 Javascript
基于layui的下拉列表的数据回显方法
Sep 24 Javascript
Node.js API详解之 os模块用法实例分析
May 06 Javascript
Taro UI框架开发小程序实现左滑喜欢右滑不喜欢效果的示例代码
May 18 Javascript
js实现键盘自动打字效果
Dec 23 #Javascript
Angularjs实现分页和分页算法的示例代码
Dec 23 #Javascript
使用Bootstrap Tabs选项卡Ajax加载数据实现
Dec 23 #Javascript
ionic开发中点击input时键盘自动弹出
Dec 23 #Javascript
JS敏感词过滤代码
Dec 23 #Javascript
关于JS Lodop打印插件打印Bootstrap样式错乱问题的解决方案
Dec 23 #Javascript
基于BootStrap栅格栏系统完成网站底部版权信息区
Dec 23 #Javascript
You might like
虹吸壶是谁发明的?煮出来的咖啡好喝吗
2021/03/04 冲泡冲煮
一个显示天气预报的程序
2006/10/09 PHP
CI(CodeIgniter)框架视图中加载视图的方法
2017/03/24 PHP
提高 DHTML 页面性能
2006/12/25 Javascript
cssQuery()的下载与使用方法
2007/01/12 Javascript
javascript web页面刷新的方法收集
2009/07/02 Javascript
Javascript面向对象之四 继承
2011/02/08 Javascript
如何获取select下拉框的值(option没有及有value属性)
2013/11/08 Javascript
js中的for如何实现foreach中的遍历
2014/05/31 Javascript
JavaScript lastIndexOf方法入门实例(计算指定字符在字符串中最后一次出现的位置)
2014/10/17 Javascript
jQuery Masonry瀑布流插件使用详解
2014/11/17 Javascript
深入分析原生JavaScript事件
2014/12/29 Javascript
jQuery中:last-child选择器用法实例
2014/12/31 Javascript
jquery图形密码实现方法
2015/03/11 Javascript
JavaScript实现简单Tip提示框效果
2016/04/20 Javascript
jquery实现下拉框左右选择功能
2017/02/21 Javascript
nodejs require js文件入口,在package.json中指定默认入口main方法
2018/10/10 NodeJs
python设计模式大全
2016/06/27 Python
从零开始学Python第八周:详解网络编程基础(socket)
2016/12/14 Python
Python3 log10()函数简单用法
2019/02/19 Python
python3对拉勾数据进行可视化分析的方法详解
2019/04/03 Python
使用Filter过滤python中的日志输出的实现方法
2019/07/17 Python
关于ResNeXt网络的pytorch实现
2020/01/14 Python
Python连接Hadoop数据中遇到的各种坑(汇总)
2020/04/14 Python
Tensorflow中k.gradients()和tf.stop_gradient()用法说明
2020/06/10 Python
keras读取训练好的模型参数并把参数赋值给其它模型详解
2020/06/15 Python
Python中使用Selenium环境安装的方法步骤
2021/02/22 Python
美国职棒大联盟的官方手套、球和头盔:Rawlings
2020/02/15 全球购物
德国净水壶和滤芯品牌:波尔德PearlCo(家用净水器)
2020/04/29 全球购物
贺卡寄语大全
2014/04/11 职场文书
大学学风建设方案
2014/05/04 职场文书
教师群众路线剖析材料
2014/09/29 职场文书
正风肃纪查摆剖析材料
2014/10/10 职场文书
2015年林业工作总结
2015/05/14 职场文书
Python如何配置环境变量详解
2021/05/18 Python
Android Studio 计算器开发
2022/05/20 Java/Android