這篇文章只是單純地講JQuery如何結合PageHelper對數據進行分頁,有時候我們需要進行多條件進行查詢數據的,因此我的下一篇文章:https://blog.csdn.net/VEclipses/article/details/104969635講了JQuery結合PageHelper含條件查詢進行分頁的,比這裏寫的要全面得多(這裏展示的js文件的內容有些bug,我改了但沒修改這裏),有興趣直接移步到那裏。
我做得功能是用戶點擊前端的模塊後,項目接收請求返回頁面給前端,在前端成功獲取頁面並加載完成時調用JQuery的ajax方法,發送獲取數據請求。服務器獲取請求之後查詢數據將數據返回給ajax的成功回調函數,在回調函數中利用JQuery技術更新頁面,並且具備查找上一頁和下一頁的功能。
配置準備工作
在pox.xml文件注入PageHelper依賴關係:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
在dao層中的配置攔截器:
<!--配置SessionFactory-->
<!--reasonable=true:分頁參數合理化,即不可能到達-1頁之類不合理的頁數-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.myhomes.entity"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<value>
helperDialect=mysql
reasonable=true
supportMethodsArguments=true
params=count=countSql
autoRuntimeDialect=true
</value>
</property>
</bean>
</array>
</property>
</bean>
1.數據庫內容
month_cost表:
booker_id爲外鍵
內容:
2.數據庫層
接口類:
package com.myhomes.dao;
import com.myhomes.entity.MonthCost;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository("monthCostDao")
public interface MonthCostDao {
MonthCost selectLastMonthMeterByHouseId(String houseId);
void insertMonthCost(MonthCost monthCost);
List<MonthCost> selectAllMonthCost();
}
映射實現文件:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.myhomes.dao.MonthCostDao">
<resultMap id="monthCost" type="MonthCost">
<id property="idNum" column="id" javaType="Integer"></id>
<result property="houseId" column="house_id" javaType="String"></result>
<result property="bookerId" column="booker_id" javaType="Integer"></result>
<result property="yearsMonth" column="years_month" javaType="java.sql.Date"></result>
<result property="rent" column="rent" javaType="Integer"></result>
<result property="waterMeter" column="water_meter" javaType="Double"></result>
<result property="powerMeter" column="power_meter" javaType="Double"></result>
<result property="network" column="network" javaType="Integer"></result>
<result property="clean" column="clean" javaType="Integer"></result>
<result property="sum" column="sums" javaType="Double"></result>
<!--<result property="deposit" column="deposit" javaType="Integer"></result>-->
<association property="users" column="booker_id" javaType="User" select="com.myhomes.dao.UserDao.selectById">
</association>
</resultMap>
<select id="selectLastMonthMeterByHouseId" parameterType="String" resultMap="monthCost">
select house_id,years_month,rent,water_meter,power_meter from month_cost where house_id = #{houseId} order by years_month desc LIMIT 0,1
</select>
<insert id="insertMonthCost" parameterType="MonthCost" useGeneratedKeys="true" keyColumn="id">
insert into month_cost(house_id,booker_id,years_month,rent,water_meter,power_meter,network,clean,sums) value
(#{houseId},#{bookerId},#{yearsMonth},#{rent},#{waterMeter},#{powerMeter},#{network},#{clean},#{sum})
</insert>
<select id="selectAllMonthCost" resultMap="monthCost">
select * from month_cost where booker_id != '' order by years_month desc
</select>
</mapper>
實體類:
package com.myhomes.entity;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class MonthCost {
private Integer idNum;
private String houseId;
private Integer bookerId;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date yearsMonth;
private Integer rent;
private double waterMeter;
private double powerMeter;
private Integer network;
private Integer clean;
private double sum;
//private Integer deposit;
private User users;
// public Integer getDeposit() {
// return deposit;
// }
//
// public void setDeposit(Integer deposit) {
// this.deposit = deposit;
// }
public Integer getIdNum() {
return idNum;
}
public void setIdNum(Integer idNum) {
this.idNum = idNum;
}
public String getHouseId() {
return houseId;
}
public void setHouseId(String houseId) {
this.houseId = houseId;
}
public Integer getBookerId() {
return bookerId;
}
public void setBookerId(Integer bookerId) {
this.bookerId = bookerId;
}
public Date getYearsMonth() {
return yearsMonth;
}
public void setYearsMonth(Date yearsMonth) {
this.yearsMonth = yearsMonth;
}
public Integer getRent() {
return rent;
}
public void setRent(Integer rent) {
this.rent = rent;
}
public double getWaterMeter() {
return waterMeter;
}
public void setWaterMeter(double waterMeter) {
this.waterMeter = waterMeter;
}
public double getPowerMeter() {
return powerMeter;
}
public void setPowerMeter(double powerMeter) {
this.powerMeter = powerMeter;
}
public Integer getNetwork() {
return network;
}
public void setNetwork(Integer network) {
this.network = network;
}
public Integer getClean() {
return clean;
}
public void setClean(Integer clean) {
this.clean = clean;
}
public double getSum() {
return sum;
}
public void setSum(double sum) {
this.sum = sum;
}
public User getUsers() {
return users;
}
public void setUsers(User users) {
this.users = users;
}
@Override
public String toString() {
return "MonthCost{" +
"houseId='" + houseId + '\'' +
", bookerId=" + bookerId +
", yearsMonth=" + yearsMonth +
", rent=" + rent +
", waterMeter=" + waterMeter +
", powerMeter=" + powerMeter +
", network=" + network +
", clean=" + clean +
", sum=" + sum +
", users=" + users +
'}';
}
}
3.服務層
接口類:
package com.myhomes.biz;
import com.myhomes.entity.MonthCost;
import java.util.List;
public interface MonthCostBiz {
MonthCost searchLastMonthMeterByHouseId(String houseId);
void addMonthCost(MonthCost monthCost);
List<MonthCost> searchAllMonthCost();
}
實現類:
package com.myhomes.biz.impl;
import com.myhomes.biz.MonthCostBiz;
import com.myhomes.dao.MonthCostDao;
import com.myhomes.entity.MonthCost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("monthCostBiz")
public class MonthCostBizImpl implements MonthCostBiz {
@Autowired
@Qualifier(value = "monthCostDao")
private MonthCostDao monthCostDao;
public MonthCost searchLastMonthMeterByHouseId(String houseId) {
return monthCostDao.selectLastMonthMeterByHouseId(houseId);
}
public void addMonthCost(MonthCost monthCost) {
monthCostDao.insertMonthCost(monthCost);
}
public List<MonthCost> searchAllMonthCost() {
return monthCostDao.selectAllMonthCost();
}
}
4.控制器層
package com.myhomes.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myhomes.biz.HouseBiz;
import com.myhomes.biz.MonthCostBiz;
import com.myhomes.entity.House;
import com.myhomes.entity.MonthCost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller("monthCostTableController")
@RequestMapping(value = "/MonthCostTable")
public class MonthCostTableController {
private Map<String,Object> result = new HashMap<>();
@Autowired
private MonthCostBiz monthCostBiz;
@Autowired
private HouseBiz houseBiz;
@RequestMapping(value = "/tolist")
public String toList(){
return "count_house_table";
}
@RequestMapping(value = "/list",params = "pageNo")
@ResponseBody
public Map<String,Object> getList(int pageNo,@RequestParam(name = "pageSize",defaultValue = "10") int pageSize){
//設置分頁參數
PageHelper.startPage(pageNo,pageSize);
//查詢所有數據
List<MonthCost> monthCostList = monthCostBiz.searchAllMonthCost();
//使用PageInfo封裝查詢結果
PageInfo<MonthCost> pageInfo = new PageInfo<MonthCost>(monthCostList);
//總記錄數
//long total = pageInfo.getTotal();
//上一頁
Integer prePage = pageInfo.getPrePage();
//下一頁
Integer nextPage = pageInfo.getNextPage();
//總數頁
Integer pages = pageInfo.getPages();
//當前頁
Integer pageNum = pageInfo.getPageNum();
//當前頁數據列表
List<MonthCost> monthCosts = pageInfo.getList();
//result.put("total",total);
result.put("monthCostList",monthCosts);
result.put("prePage",prePage);
result.put("nextPage",nextPage);
result.put("pages",pages);
result.put("pageNum",pageNum);
List<House> houseList = houseBiz.searchAllHouseId();
result.put("houseList",houseList);
return result;
}
}
5.前端
頁面:
top.jsp:
<li id="manager_a"><b>基本管理</b></li>
<a id="user_manager_a" href="/user/listAll">人員管理</a>
<a id="house_manager_a" href="/house/listAll">房間管理</a>
<a id="send_manager_a" href="">留言管理</a>
<li id="service_li"><b>業務管理</b></li>
<a id="count_a" onclick="javascript:window.location.href='/count/view';">計算房租</a>
<a id="sum_a" onclick="javascript:window.location.href='/MonthCostTable/tolist';">查看房租</a>
數據頁面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<jsp:include page="top.jsp"></jsp:include>
<section id="right">
<a id="user_local">
業務管理 -> 每月房租
</a>
<div id="list_mean_div">
<form>
<div id="list_div_top"></div>
<a id="name_a"><b>租客名字:</b></a>
<input id="month_cost_name_text" type="text" name="name" maxlength="20" placeholder="輸入租客名字..."/>
<a id="month_cost_house_a"><b>房號:</b></a>
<select id="month_cost_house_select" name="houseId">
<%--selected:默認選擇該選項;--%>
<%--disabled:該選項不能被鼠標選擇;(注:選項沒有被隱藏的時候)--%>
<%--style="display:none":隱藏該選項;(注:該選項不會出現在下拉列)--%>
<%--value="":該選項value爲“”;(注:可做表單驗證)--%>
<option selected disabled style="display:none" value="">選擇房號</option>
</select>
<button id="month_cost_search_button" type="submit">搜索</button>
<label id="month_cost_label" style="color: red;">注意:月總金額包含清潔費10元,水費2.5元/度,電費1.5元/度。</label>
</form>
<br/><br/><br/>
<hr/>
</div>
<div id="month_cost_table_div">
<table id="month_cost_table" border="0" cellpadding="0" cellspacing="0">
<colgroup>
<col align="center" width="0px" hidden>
<col align="center" width="75px">
<col align="center" width="50px">
<col align="center" width="75px">
<col align="center" width="40px">
<col align="center" width="50px">
<col align="center" width="50px">
<col align="center" width="30px">
<col align="center" width="40px">
<col align="center" width="40px">
</colgroup>
<thead>
<tr>
<th hidden>id</th>
<th>房客姓名</th>
<th>房間號</th>
<th>記錄房租時間</th>
<th>月租金</th>
<th>水錶數</th>
<th>電錶數</th>
<th>網費</th>
<th>月總金額</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script src="/js/monthCountTable.js"></script>
</section>
<jsp:include page="buttom.jsp"></jsp:include>
js部分:
這裏有個小bug,在點擊下一頁和上一頁的時候沒有替換掉原來的div,導致生成多個div,只是他們都疊在一起頁面上看不出來。
$(document).ready(function(){
$.ajax({
type:"get",
url:"/MonthCostTable/list?pageNo=1",
success:function (data) {
for (var i = 0;i < data.houseList.length;i++){
var houseIdList = "<option value='" + data.houseList[i].houseId + "'>" + data.houseList[i].houseId + "</option>";
$("select").append(houseIdList);
}
if(data.monthCostList != null){
for (var i = 0;i < data.monthCostList.length ;i++){
var monthCostList = "<tr>"+
"<td hidden>"+data.monthCostList[i].idNum+"</td>"+
"<td align='center'>"+data.monthCostList[i].users.name+"</td>"+
"<td align='center'>"+data.monthCostList[i].houseId+"</td>"+
"<td align='center'>"+data.monthCostList[i].yearsMonth+"</td>"+
"<td align='center'>"+data.monthCostList[i].rent+"</td>"+
"<td align='center'>"+data.monthCostList[i].waterMeter+"</td>"+
"<td align='center'>"+data.monthCostList[i].powerMeter+"</td>"+
"<td align='center'>"+data.monthCostList[i].network+"</td>"+
"<td align='center'>"+data.monthCostList[i].sum+"</td>"+
"<td align='center' id='updelect_td'><a id='update_a' href='/MonthCostTable/to_update?id="+data.monthCostList[i].idNum+"' id='update_a'>修改</a></td>"+
"</tr>";
$("tbody").append(monthCostList);
}
var page = "<div style='position: absolute;background-color: white;width: 1100px;height: 23px;'>"+
"<a id='pageNum'>當前第"+data.pageNum+"頁,一共有"+data.pages+"頁</a>"+
"<a id='data_pageNum' hidden>"+data.pageNum+"</a>"+
"<a id='data_pages' hidden>"+data.pages+"</a>"+
"<a id='beforePage' onclick='myPrePage()'>上一頁</a>"+
"<a id='data_prePage' hidden>"+data.prePage+"</a>"+
"<a id='nextPage' onclick='myNextPage()'>下一頁</a>"+
"<a id='data_nextPage' hidden>"+data.nextPage+"</a>"+
"</div>";
$("table").append(page);
}else if (data.monthCostList == null) {
var html = "<tr><td align='center' colspan='8'>沒有查找到任何數據</td></tr><td><br><br></td>";
$("tbody").append(html);
}else{
alert("系統出錯!");
}
}
});
});
//點擊上一頁執行的代碼
function myPrePage() {//alert("當前頁:"+$("#data_pageNum").text()+"當前頁的上一頁:"+$("#data_prePage").text()+"當前頁的下一頁:"+$("#data_nextPage").text());
//如果上一頁頁碼爲0,則return false;
//上一頁頁碼
var prePage = $("#data_prePage").text();
//alert("上一頁頁碼:"+prePage);
if (prePage !== "0"){
$.ajax({
type:"get",
url:"/MonthCostTable/list?pageNo="+prePage,
success:function (data) {
for (var i = 0;i < data.houseList.length;i++){
var houseIdList = "<option value='" + data.houseList[i].houseId + "'>" + data.houseList[i].houseId + "</option>";
$("select").append(houseIdList);
}
if(data.monthCostList != null){
for (var i = 0;i < data.monthCostList.length ;i++){
var monthCostList = "<tr>"+
"<td hidden>"+data.monthCostList[i].idNum+"</td>"+
"<td align='center'>"+data.monthCostList[i].users.name+"</td>"+
"<td align='center'>"+data.monthCostList[i].houseId+"</td>"+
"<td align='center'>"+data.monthCostList[i].yearsMonth+"</td>"+
"<td align='center'>"+data.monthCostList[i].rent+"</td>"+
"<td align='center'>"+data.monthCostList[i].waterMeter+"</td>"+
"<td align='center'>"+data.monthCostList[i].powerMeter+"</td>"+
"<td align='center'>"+data.monthCostList[i].network+"</td>"+
"<td align='center'>"+data.monthCostList[i].sum+"</td>"+
"<td align='center' id='updelect_td'><a id='update_a' href='/MonthCostTable/to_update?id="+data.monthCostList[i].idNum+"' id='update_a'>修改</a></td>"+
"</tr>";
$("tbody").html();
$("tbody").append(monthCostList);
}
var page = "<div style='position: absolute;background-color: white;width: 1100px;height: 23px;'>"+
"<a id='pageNum'>當前第"+data.pageNum+"頁,一共有"+data.pages+"頁</a>"+
"<a id='beforePage' onclick='myPrePage()'>上一頁</a>"+
"<a id='nextPage' onclick='myNextPage()'>下一頁</a>"+
"</div>";
$("#data_pageNum").text(data.pageNum);
$("#data_pages").text(data.pages);
$("#data_prePage").text(data.prePage);
$("#data_nextPage").text(data.nextPage);
$("table").append(page);
}else{
alert("系統出錯!");
}
}
});
}else {
alert("當前頁爲首頁");
}
}
//點擊下一頁執行的代碼
function myNextPage() {//alert("當前頁:"+$("#data_pageNum").text()+"當前頁的上一頁:"+$("#data_prePage").text()+"當前頁的下一頁:"+$("#data_nextPage").text());
//如果當前頁碼與總頁碼不同,則獲取下一頁頁碼,並查找;如果當前頁碼與總頁碼相同,則return false;
//當前頁碼
var pageNum = $("#data_pageNum").text();
//總頁碼
var pages = $("#data_pages").text();
//下一頁頁碼
var nextPage = $("#data_nextPage").text();
if (pageNum !== pages) {
$.ajax({
type:"get",
url:"/MonthCostTable/list?pageNo="+nextPage,
success:function (data) {
for (var i = 0;i < data.houseList.length;i++){
var houseIdList = "<option value='" + data.houseList[i].houseId + "'>" + data.houseList[i].houseId + "</option>";
$("select").append(houseIdList);
}
if(data.monthCostList != null){
for (var i = 0;i < data.monthCostList.length ;i++){
var monthCostList = "<tr>"+
"<td hidden>"+data.monthCostList[i].idNum+"</td>"+
"<td align='center'>"+data.monthCostList[i].users.name+"</td>"+
"<td align='center'>"+data.monthCostList[i].houseId+"</td>"+
"<td align='center'>"+data.monthCostList[i].yearsMonth+"</td>"+
"<td align='center'>"+data.monthCostList[i].rent+"</td>"+
"<td align='center'>"+data.monthCostList[i].waterMeter+"</td>"+
"<td align='center'>"+data.monthCostList[i].powerMeter+"</td>"+
"<td align='center'>"+data.monthCostList[i].network+"</td>"+
"<td align='center'>"+data.monthCostList[i].sum+"</td>"+
"<td align='center' id='updelect_td'><a id='update_a' href='/MonthCostTable/to_update?id="+data.monthCostList[i].idNum+"' id='update_a'>修改</a></td>"+
"</tr>";
$("tbody").html(monthCostList);
}
var page = "<div style='position: absolute;background-color: white;width: 1100px;height: 23px;'>"+
"<a id='pageNum'>當前第"+data.pageNum+"頁,一共有"+data.pages+"頁</a>"+
"<a id='beforePage' onclick='myPrePage()'>上一頁</a>"+
"<a id='nextPage' onclick='myNextPage()'>下一頁</a>"+
"</div>";
$("#data_pageNum").text(data.pageNum);
$("#data_pages").text(data.pages);
$("#data_prePage").text(data.prePage);
$("#data_nextPage").text(data.nextPage);
$("table").append(page);
}else{
alert("系統出錯!");
}
}
});
}else{
alert("已經是最後一頁了!");
}
}
6.演示
步驟一、啓動項目後訪問網站
這裏是登錄後的頁面
步驟二、點擊“查看房租”
步驟三、測試點擊上一頁是否有問題
如果數據的是第一頁,則不用訪問服務器,讓服務器減少不必要的接收用戶請求操作。
步驟四、測試點擊下一頁
XHR不爲空,沒毛病。
開發者工具查看接收的數據:
第二頁獲取到了一條數據。
步驟五、頁尾測試點擊下一頁
無意義的操作就在前端攔截了,沒有交給服務器處理,右側XHR沒有新增。
步驟六、測試點擊上一頁
右側XHR多了條數據。
開發者工具查看:
數據正好10條
7.後言
如有不懂可留言,如果幫到你就點個贊吧~~