SSH(Spring+Struts+Hibernate)框架学习之分页技术的实现

来源:互联网 发布:数据分析属经济学吗 编辑:程序博客网 时间:2024/06/06 17:39

其实在Coding中,有很多东西都是因为需要这么做,然后不会做,去看别人怎么做,然后做一个比别人更华丽的“轮子”。

我这里简单介绍一下自己的分页技术的实现

首先创建一个Page.java的实体类 。

package com.lrms.entity;/** * @author songyx * */public class Page {private int everyPage;      //每页记录数private int totalCount;     //总记录数private int totalPage;      //总页数private int currentPage;    //当前页码private int beginIndex;     //开始的记录数private boolean hasPrePage; //是否有上一页private boolean hasNextPage;//是否有下一页public Page(int everyPage, int totalCount, int totalPage, int currentPage,int beginIndex, boolean hasPrePage, boolean hasNextPage) {this.everyPage = everyPage;this.totalCount = totalCount;this.totalPage = totalPage;this.currentPage = currentPage;this.beginIndex = beginIndex;this.hasPrePage = hasPrePage;this.hasNextPage = hasNextPage;}public Page(){}public int getEveryPage() {return everyPage;}public void setEveryPage(int everyPage) {this.everyPage = everyPage;}public int getTotalCount() {return totalCount;}public void setTotalCount(int totalCount) {this.totalCount = totalCount;}public int getTotalPage() {return totalPage;}public void setTotalPage(int totalPage) {this.totalPage = totalPage;}public int getCurrentPage() {return currentPage;}public void setCurrentPage(int currentPage) {this.currentPage = currentPage;}public int getBeginIndex() {return beginIndex;}public void setBeginIndex(int beginIndex) {this.beginIndex = beginIndex;}public boolean isHasPrePage() {return hasPrePage;}public void setHasPrePage(boolean hasPrePage) {this.hasPrePage = hasPrePage;}public boolean isHasNextPage() {return hasNextPage;}public void setHasNextPage(boolean hasNextPage) {this.hasNextPage = hasNextPage;}}

然后创建一个PageUtil.java的工具类

package com.lrms.util;import com.lrms.entity.Page;public class PageUtil {public static Page createPage(int everyPage,int totalCount,int currentPage) {everyPage = getEveryPage(everyPage);currentPage = getCurrentPage(currentPage);int totalPage = getTotalPage(everyPage, totalCount);int beginIndex = getBeginIndex(everyPage, currentPage);boolean hasPrePage = getHasPrePage(currentPage);boolean hasNextPage = getHasNextPage(totalPage, currentPage);return new Page(everyPage, totalCount, totalPage, currentPage,beginIndex, hasPrePage,  hasNextPage);}public static Page createPage(Page page,int totalCount) {int everyPage = getEveryPage(page.getEveryPage());int currentPage = getCurrentPage(page.getCurrentPage());int totalPage = getTotalPage(everyPage, totalCount);int beginIndex = getBeginIndex(everyPage, currentPage);boolean hasPrePage = getHasPrePage(currentPage);boolean hasNextPage = getHasNextPage(totalPage, currentPage);return new Page(everyPage, totalCount, totalPage, currentPage,beginIndex, hasPrePage,  hasNextPage);}//设置每页显示记录数public static int getEveryPage(int everyPage) {return everyPage == 0 ? 10 : everyPage;}//设置当前页public static int getCurrentPage(int currentPage) {return currentPage == 0 ? 1 : currentPage;}//设置总页数,需要总记录数,每页显示多少public static int getTotalPage(int everyPage,int totalCount) {int totalPage = 0;if(totalCount % everyPage == 0) {totalPage = totalCount / everyPage;} else {totalPage = totalCount / everyPage + 1;}return totalPage;}//设置起始点,需要每页显示多少,当前页public static int getBeginIndex(int everyPage,int currentPage) {return (currentPage - 1) * everyPage;}//设置是否有上一页,需要当前页public static boolean getHasPrePage(int currentPage) {return currentPage == 1 ? false : true;}//设置是否有下一个,需要总页数和当前页public static boolean getHasNextPage(int totalPage, int currentPage) {return currentPage == totalPage || totalPage == 0 ? false : true;}}

这两个类就足够我们用的了。我这里以一个实验室的检索为例

实验室的实体类Room

package com.lrms.entity;/** * @author songyx * */public class Room {private int id;private int stuNum;        //容纳人数private String name;       //名称private String location;   //位置private String remark;     //备注private int state;         //状态      非持久化字段,数据库里边没有这个字段public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getLocation() {return location;}public void setLocation(String location) {this.location = location;}public String getRemark() {return remark;}public void setRemark(String remark) {this.remark = remark;}public int getStuNum() {return stuNum;}public void setStuNum(int stuNum) {this.stuNum = stuNum;}public int getState() {return state;}public void setState(int state) {this.state = state;}}
DAO层接口类
package com.lrms.dao;import java.util.List;import com.lrms.entity.Page;import com.lrms.entity.Room;/** * @author songyx * */public interface RoomDAO {public Room findRoomById(int id);public List<Room> queryByPage(final Page page);public int roomCounts();public void update(Room room);public void delete(Room room);public void save(Room room);}
DAO层实现类

package com.lrms.dao.impl;import java.sql.SQLException;import java.util.List;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.springframework.orm.hibernate3.HibernateCallback;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import com.lrms.dao.RoomDAO;import com.lrms.entity.Page;import com.lrms.entity.Room;/** * @author songyx * */public class RoomDAOImpl extends HibernateDaoSupport implements RoomDAO{@Overridepublic Room findRoomById(int id) {return this.getHibernateTemplate().get(Room.class, id);}@SuppressWarnings({ "unchecked", "rawtypes" })@Overridepublic List<Room> queryByPage(Page page) {return (List<Room>)this.getHibernateTemplate().executeFind(new HibernateCallback(){              public Object doInHibernate(Session session)                      throws HibernateException, SQLException {                  Query query = session.createQuery("from Room r order by r.id desc");                  query.setFirstResult(page.getBeginIndex());                  query.setMaxResults(page.getEveryPage());                  return query.list();              }        }); }@Overridepublic int roomCounts() {int rowTotal=0;rowTotal = ((Long)this.getHibernateTemplate().find("select count(*) from Room").get(0)).intValue();return rowTotal;}@Overridepublic void update(Room room) {this.getHibernateTemplate().update(room);}@Overridepublic void delete(Room room) {this.getHibernateTemplate().delete(room);}@Overridepublic void save(Room room) {this.getHibernateTemplate().save(room);}}


Service层接口类

package com.lrms.service;import java.util.List;import com.lrms.entity.Page;import com.lrms.entity.Room;/** * @author songyx * */public interface RoomService {public Room findRoomById(int id);public List<Room> queryByPage(final Page page);public int roomCounts();public void update(Room room);public void delete(Room room);public void save(Room room);}

Service层实现类

package com.lrms.service.impl;import java.util.List;import com.lrms.dao.RoomDAO;import com.lrms.entity.Page;import com.lrms.entity.Room;import com.lrms.service.RoomService;/** * @author songyx * */public class RoomServiceImpl implements RoomService{private RoomDAO roomDao;public RoomDAO getRoomDao() {return roomDao;}public void setRoomDao(RoomDAO roomDao) {this.roomDao = roomDao;}@Overridepublic Room findRoomById(int id) {return this.getRoomDao().findRoomById(id);}@Overridepublic List<Room> queryByPage(Page page) {return this.getRoomDao().queryByPage(page);}@Overridepublic int roomCounts() {return this.getRoomDao().roomCounts();}@Overridepublic void update(Room room) {this.getRoomDao().update(room);}@Overridepublic void delete(Room room) {this.getRoomDao().delete(room);}@Overridepublic void save(Room room) {this.getRoomDao().save(room);}}

Controller 中的Action写法

package com.lrms.action.room;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.apache.struts2.ServletActionContext;import com.lrms.entity.Page;import com.lrms.entity.Room;import com.lrms.service.RoomService;import com.lrms.util.PageUtil;import com.opensymphony.xwork2.ActionSupport;/** * @author songyx * */public class ScanRoomAction extends ActionSupport{private static final long serialVersionUID = 7236063679821783012L;private Room room;private Page roomPage;private int currentPage;private RoomService roomService;private final int everyPage=10;public Room getRoom() {return room;}public void setRoom(Room room) {this.room = room;}public Page getRoomPage() {return roomPage;}public void setRoomPage(Page roomPage) {this.roomPage = roomPage;}public int getCurrentPage() {return currentPage;}public void setCurrentPage(int currentPage) {this.currentPage = currentPage;}public RoomService getRoomService() {return roomService;}public void setRoomService(RoomService roomService) {this.roomService = roomService;}public int getEveryPage() {return everyPage;}public String execute(){HttpServletRequest request = ServletActionContext.getRequest();HttpSession session=request.getSession();int totalCount=this.roomService.roomCounts();setRoomPage(PageUtil.createPage(everyPage, totalCount, 0));List<Room> rooms=this.roomService.queryByPage(roomPage);session.setAttribute("rooms", rooms);session.setAttribute("roomPage", roomPage);return SUCCESS;}public String nextPage(){//下一页HttpServletRequest request = ServletActionContext.getRequest();HttpSession session=request.getSession();int totalCount=this.roomService.roomCounts();roomPage=PageUtil.createPage(everyPage, totalCount, currentPage+1);List<Room> rooms=this.roomService.queryByPage(roomPage);session.setAttribute("rooms", rooms);session.setAttribute("roomPage", roomPage);return "NextPage";}public String frontPage(){HttpServletRequest request = ServletActionContext.getRequest();HttpSession session=request.getSession();int totalCount=this.roomService.roomCounts();roomPage=PageUtil.createPage(everyPage, totalCount,currentPage-1);List<Room> rooms=this.roomService.queryByPage(roomPage);session.setAttribute("rooms", rooms);session.setAttribute("roomPage", roomPage);return "frontPage";}}


其中通过用户首次查询执行action中的execute方法。方法中首先查询出查询结果的总记录数

int totalCount=this.roomService.roomCounts();
然后创建page对象,我们这里默认的everyPage=10,也就是每页显示的记录数是10,然后通过page对象自动创建page的其他属性值。

然后我们通过page进行查询,就可根据不同的页码、不同的查询条件,得到不同的查询结果。

显示结果的jsp页面源码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib uri="/struts-tags" prefix="s"%><%String path = request.getContextPath();int i=0;%><!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>实验室管理</title>    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta name="description" content="">    <meta name="author" content="">    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/lib/bootstrap/css/bootstrap.css">    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/stylesheets/theme.css">    <link rel="stylesheet" href="${pageContext.request.contextPath}/lib/font-awesome/css/font-awesome.css">    <script src="${pageContext.request.contextPath}/lib/jquery-1.8.1.min.js" type="text/javascript"></script><script src="${pageContext.request.contextPath}/javascripts/layer/layer.js" type="text/javascript"></script>    <!-- Demo page code -->        <style type="text/css">        #line-chart {            height:300px;            width:800px;            margin: 0px auto;            margin-top: 1em;        }        .brand { font-family: georgia, serif; }        .brand .first {            color: #ccc;            font-style: italic;        }        .brand .second {            color: #fff;            font-weight: bold;        }    </style><script type="text/javascript">window.id=0;function addRoom(){window.location.href='${pageContext.request.contextPath}/admin/addroom.jsp';}function confirm(id){window.id=id;}function deleteTc(){$.post("roomservice!delete.action",{'id':window.id},function(result){if(result.stateCode==1){layer.msg(result.message, {icon: 4});window.location.href='scanroom';}else{layer.msg(result.message, {icon: 2});}},"json");}</script>    <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->    <!--[if lt IE 9]>      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>    <![endif]-->    <!-- Le fav and touch icons -->    <link rel="shortcut icon" href="${pageContext.request.contextPath}/assets/ico/favicon.ico">    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="${pageContext.request.contextPath}/assets/ico/apple-touch-icon-144-precomposed.png">    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="${pageContext.request.contextPath}/assets/ico/apple-touch-icon-114-precomposed.png">    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="${pageContext.request.contextPath}/assets/ico/apple-touch-icon-72-precomposed.png">    <link rel="apple-touch-icon-precomposed" href="${pageContext.request.contextPath}/assets/ico/apple-touch-icon-57-precomposed.png">  </head>  <!--[if lt IE 7 ]> <body class="ie ie6"> <![endif]-->  <!--[if IE 7 ]> <body class="ie ie7"> <![endif]-->  <!--[if IE 8 ]> <body class="ie ie8"> <![endif]-->  <!--[if IE 9 ]> <body class="ie ie9"> <![endif]-->  <!--[if (gt IE 9)|!(IE)]><!-->   <body>   <!--<![endif]-->        <div class="navbar">        <div class="navbar-inner">            <div class="container-fluid">                <ul class="nav pull-right">                                        <li id="fat-menu" class="dropdown">                        <a href="#" id="drop3" role="button" class="dropdown-toggle" data-toggle="dropdown">                            <i class="icon-user"></i> ${user.name}                            <i class="icon-caret-down"></i>                        </a>                        <ul class="dropdown-menu">                        <s:if test="#session.user.type==3">                        <li><a tabindex="-1" href="adminservice!edit.action?id=<s:property value="#session.user.id" />">个人信息</a></li>                        </s:if>                            <s:elseif test="#session.user.type==2">                            <li><a tabindex="-1" href="teacherservice!edit.action?id=<s:property value="#session.user.id" />">个人信息</a></li>                            </s:elseif>                            <s:elseif test="#session.user.type==1">                            <li><a tabindex="-1" href="studentservice!edit.action?id=<s:property value="#session.user.id" />">个人信息</a></li>                            </s:elseif>                            <li class="divider"></li>                            <li><a tabindex="-1" href="Login!logout.action">注销</a></li>                        </ul>                    </li>                                    </ul>                <a class="brand" href="index.jsp"><span class="first">实验室</span> <span class="second">预约管理系统</span></a>            </div>        </div>    </div>        <div class="container-fluid">                <div class="row-fluid">            <div class="span3">                <div class="sidebar-nav">                  <div class="nav-header" data-toggle="collapse" data-target="#dashboard-menu"><i class="icon-dashboard"></i>预约管理</div>                    <ul id="dashboard-menu" class="nav nav-list collapse in">                        <s:if test="#session.user.type==3">                        <li><a href="scancourse?type=2">未审核预约</a></li>                        <li><a href="scancourse?type=0">预约记录</a></li>                        </s:if>                        <s:if test="#session.user.type==1">                        <li><a href="courseservice!book.action">预约</a></li>                        <li><a href="scancourse?type=0">预约记录</a></li>                        </s:if>                        <s:if test="#session.user.type==2">                                             <li><a href="scancourse?type=0">预约记录</a></li>                        </s:if>                    </ul>                <div class="nav-header" data-toggle="collapse" data-target="#accounts-menu"><i class="icon-briefcase"></i>查看课表</div>                <ul id="accounts-menu" class="nav nav-list collapse in">                  <li ><a href="scancourse?type=1">查看课表</a></li>                </ul>                <s:if test="#session.user.type!=1"><div class="nav-header" data-toggle="collapse" data-target="#account-menu"><i class="icon-briefcase"></i>人员管理</div>                <ul id="account-menu" class="nav nav-list collapse in">                  <s:if test="#session.user.type==3">                  <li ><a href="${pageContext.request.contextPath}/admin/addadmin.jsp">增加管理员</a></li>                  <li ><a href="scanadmin">管理员管理</a></li>                  <li ><a href="${pageContext.request.contextPath}/admin/addteacher.jsp">增加教师</a></li>                  <li ><a href="scanteacher">教师管理</a></li>                  </s:if>                  <s:if test="#session.user.type==2">                  <li ><a href="studentservice!edit.action">设置课代表</a></li>                  </s:if>                  <li ><a href="scanstudent">查看课代表</a></li>                </ul>                </s:if>                 <s:if test="#session.user.type==3">                <div class="nav-header" data-toggle="collapse" data-target="#settings-menu"><i class="icon-exclamation-sign"></i>实验室管理</div>                <ul id="settings-menu" class="nav nav-list collapse in">                  <li ><a href="scanroom">实验室管理</a></li>              <li ><a href="${pageContext.request.contextPath}/admin/addroom.jsp">添加实验室</a></li>                </ul>                </s:if>            </div>                    </div>        <div class="span9">            <h1 class="page-title">实验室管理</h1><div class="btn-toolbar">    <s:if test="#session.user.type==3">    <button class="btn btn-primary" onclick="addRoom();"><i class="icon-plus"></i> 增加实验室</button>  </s:if>  <div class="btn-group">  </div></div><div class="well">    <table class="table">      <thead>        <tr>          <th>#</th>          <th>实验室名称</th>          <th>位置</th>          <th>容纳人数</th>          <th>备注</th>          <th style="width: 26px;"></th>        </tr>      </thead>      <tbody>      <s:iterator value="#session.rooms" id="infos">      <tr>      <td><%=++i%></td>      <td><a href="roomservice!edit.action?id=<s:property value="#infos.id" />"><s:property value="#infos.name" /></a></td><td><s:property value="#infos.location" /></td><td><s:property value="#infos.stuNum" /></td>          <td><s:property value="#infos.remark" /></td>          <s:if test="#session.user.type==3">          <td>            <a href="roomservice!edit.action?id=<s:property value="#infos.id" />"><i class="icon-pencil"></i></a>            <a href="#myModal" role="button" data-toggle="modal" onclick="confirm(<s:property value="#infos.id" />)"><i class="icon-remove"></i></a>        </td>        </s:if></tr></s:iterator>      </tbody>    </table></div><div class="pagination">    <ul><s:if test="#request.roomPage.hasPrePage==true"><li><a href="scanroom!frontPage.action?currentPage=<s:property value="roomPage.currentPage" />" class="btu">上一页</a></li></s:if><li><a href="#" class="btu active"><s:property value="roomPage.currentPage" /></a></li><s:if test="#request.roomPage.currentPage+1<=#request.roomPage.totalPage"><li><a href="scanroom!nextPage.action?currentPage=<s:property value="roomPage.currentPage" />" class="btu"><s:property value="roomPage.currentPage+1" /></a></li></s:if><s:if test="#request.roomPage.currentPage+2<=#request.roomPage.totalPage"><li><a href="scanroom!nextPage.action?currentPage=<s:property value="roomPage.currentPage+1" />" class="btu"><s:property value="roomPage.currentPage+2" /></a></li></s:if><s:if test="#request.roomPage.currentPage+3<=#request.roomPage.totalPage"><li><a href="scanroom!nextPage.action?currentPage=<s:property value="roomPage.currentPage+2" />" class="btu"><s:property value="roomPage.currentPage+3" /></a></li></s:if><s:if test="#request.roomPage.hasNextPage==true"><li><a href="scanroom!nextPage.action?currentPage=<s:property value="roomPage.currentPage" />" class="btu">下一页</a></li></s:if>    </ul></div><div class="modal small hide fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">    <div class="modal-header">        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>        <h3 id="myModalLabel">警告</h3>    </div>    <div class="modal-body">        <p class="error-text"><i class="icon-warning-sign modal-icon"></i>确定要删除这条信息吗?</p>    </div>    <div class="modal-footer">        <button class="btn" data-dismiss="modal" aria-hidden="true">取消</button>        <button class="btn btn-danger" data-dismiss="modal" onclick="deleteTc();">确定</button>    </div></div>        </div>    </div></div>   <footer>        <hr>        <p class="pull-right">Copyright <a title="内蒙古大学" target="_blank">内蒙古大学</a></p>        <p>&copy; 2017 <a>内蒙古大学</a></p>    </footer>    <script src="${pageContext.request.contextPath}/lib/bootstrap/js/bootstrap.js"></script>  </body></html>


显示结果:






阅读全文
0 0
原创粉丝点击