springboot + mybatis 分頁插件(Pagehelper)


方法一:使用pagehelper-spring-boot-starter的形式(最簡單和通用的方式)
使用步驟:

(1)在pom.xml文件中引入依賴庫

<!-- 分頁插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
(2)在application.properties中添加分頁配置

# 配置pageHelper分頁插件的內容
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql
或者在application.yml文件中添加分頁配置

pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
(3)進行使用。(可以在controller層或者service層使用即可)

/**
* 查詢所有的person內容
* @return
*/
@RequestMapping(value = "/list")
public String jumpJsp(Map<String, Object> result){
PageHelper.startPage(3 , 3);
List<Person> personList = personService.findPerson();
//得到分頁的結果對象
PageInfo<Person> personPageInfo = new PageInfo<>(personList);
//得到分頁中的person條目對象
List<Person> pageList = personPageInfo.getList();
//將結果存入map進行傳送
result.put("pageInfo" , pageList);
return "person_list";
}
解析:

(1)PageHelper.startPage(pageNum , pageSize),這個方法就是類似我們數據庫操作的limit start , count

(2)得到的對象PageInfo里面包含很多的字段信息,這個可以自己看源碼,非常詳細

(3)如果我們只想得到分頁處理之后我們的實體對象的結果,那么就調用PageInfo對象的getList()方法即可。

(4)這種配置使用的方式是最通用的方式,也就是對於環境搭建不同方式都可以利用這種使用方法。

問題:如果運行時出現,org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration': 這個錯誤。

解決辦法:這是由於分頁插件pagehelper的版本和mybatis不兼容的原因,修改分頁插件的版本即可。

 

 

方法二:使用最原始的形式(SpringBoot+Mybatis配置文件的形式,也就是整合環境還是利用xml的形式搭建的,但是都是通過@configuration注解開發類)
使用步驟:

(1)在pom.xml文件中,添加分頁插件的依賴(注意和第一種方法的區別)

<!-- 分頁插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
(2)在mybatis的配置文件中添加如下的插件

<!-- 配置mybatis的分頁插件PageHelper -->
<plugins>
<!-- com.github.pagehelper為PageHelper類所在包名 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 設置數據庫類型Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種數據庫 -->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
(3)在controller或者service層進行使用插件

/**
* 查詢所有的person內容
* @return
*/
@RequestMapping(value = "/list")
public String jumpJsp(Map<String, Object> result){
PageHelper.startPage(1 , 5);
List<Person> personList = personService.findPerson();
//得到分頁的結果對象
PageInfo<Person> personPageInfo = new PageInfo<>(personList);
//得到分頁中的person條目對象
List<Person> pageList = personPageInfo.getList();
//將結果存入map進行傳送
result.put("pageInfo" , pageList);
return "person_list";
}
分析:對於這種方法的話,適用於對整合環境還是通過mybatis.xml的形式,所以,這種是具有針對性的一種情況。
方法三:使用最原始的方式(SpringBoot+Mybatis搭建中,Mybatis是利用在application.properties進行設置,並且mapper文件的操作還是使用.xml形式編寫的sql語句,而非mapper注解編寫)
使用步驟:

(1)在pom.xml文件中添加分頁插件的依賴

<!-- 分頁插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
(2)添加下面一個類

package com.hnu.scw.config;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

/**
* @ Author :scw
* @ Date :Created in 下午 2:48 2018/6/17 0017
* @ Description:用於配置分頁插件的使用
* @ Modified By:
* @Version: $version$
*/
@Configuration
public class PgeHeplerConfig {
//將分頁插件注入到容器中
@Bean
public PageHelper pageHelper() {
//分頁插件
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("reasonable", "true");
properties.setProperty("supportMethodsArguments", "true");
properties.setProperty("returnPageInfo", "check");
properties.setProperty("params", "count=countSql");
pageHelper.setProperties(properties);

//添加插件
new SqlSessionFactoryBean().setPlugins(new Interceptor[]{pageHelper});
return pageHelper;
}

}
或者如下的代碼:

package com.hnu.scw.config;
import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;

/**
* @ Author :scw
* @ Date :Created in 下午 2:48 2018/6/17 0017
* @ Description:用於配置分頁插件的使用
* @ Modified By:
* @Version: $version$
*/
@Configuration
public class PgeHeplerConfig {
//將分頁插件注入到容器中
@Bean
public PageHelper pageHelper() {
//分頁插件
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("reasonable", "true");
properties.setProperty("supportMethodsArguments", "true");
properties.setProperty("helperDialect", "mysql");
properties.setProperty("params", "count=countSql");
pageHelper.setProperties(properties);
return pageHelper;
}

}
還可以直接在springboot的啟動類添加下面的代碼即可。(其實都一樣的道理,因為上面的類都是用了@Configuration注解配置了的,也就是添加到了容器中)

//將分頁插件注入到容器中
@Bean
public PageHelper pageHelper() {
//分頁插件
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("reasonable", "true");
properties.setProperty("supportMethodsArguments", "true");
properties.setProperty("helperDialect", "mysql");
properties.setProperty("params", "count=countSql");
pageHelper.setProperties(properties);
return pageHelper;
}
(3)直接使用

/**
* 查詢所有的person內容
* @return
*/
@RequestMapping(value = "/list")
public String jumpJsp(Map<String, Object> result){
PageHelper.startPage(1 , 5);
List<Person> personList = personService.findPerson();
//得到分頁的結果對象
PageInfo<Person> personPageInfo = new PageInfo<>(personList);
//得到分頁中的person條目對象
List<Person> pageList = personPageInfo.getList();
//將結果存入map進行傳送
result.put("pageInfo" , pageList);
return "person_list";
}
情景二:Spring+SpringMVC+Mybatis+Maven環境
使用步驟:(其實這個就類似情景一種的方式二,換湯不換葯)

(1)在pom.xml中添加分頁插件的依賴

<!-- 分頁插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
(2)在mybatis中的配置文件SqlMapConfig.xml(這個名字是你自己搭建環境所取的,就是配置一些關於Mybatis的配置文件)添加分頁插件。

<!-- 配置mybatis的分頁插件PageHelper -->
<plugins>
<!-- com.github.pagehelper為PageHelper類所在包名 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 設置數據庫類型Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種數據庫 -->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
(3)在controller層或者service實現層中使用分頁。

/**
* 查詢所有的person內容
* @return
*/
@RequestMapping(value = "/list")
public String jumpJsp(Map<String, Object> result){
PageHelper.startPage(1 , 8);
List<Person> personList = personService.findPerson();
//得到分頁的結果對象
PageInfo<Person> personPageInfo = new PageInfo<>(personList);
//得到分頁中的person條目對象
List<Person> pageList = personPageInfo.getList();
//將結果存入map進行傳送
result.put("pageInfo" , pageList);
return "person_list";
}
總結:
(1)pagehelper插件本身就是基於Mybatis這種框架進行開發的插件。所以,主要都是針對Mybatis數據操作的架構的。

(2)上面描述了多種情況的具體配置方式,都是自身經過實際開發編寫的,而且對於不同的情景,各位要理解為什么要這樣,這雖然只是講解了分頁插件的使用,當遇到其他插件的時候,都可以類似進行處理。

(3)如果是用到的SSH(Spring+SpringMVC+Hibernate)或者SpringBoot+Hibernate這樣的架構的時候,這個插件是無法使用的,就需要自己通過hibernate的形式進行處理,比如可以用HQL語法或者Criteria進行處理即可。畢竟,Hibernate是一種全自動化的數據庫操作框架。

 

下面的內容,是關於原始方式實現分頁效果,僅供各位進行參考(其中是通過實例來幫助大家進行分析)

實現方法一:通過自定義分頁標簽(JSP)
分頁,這個功能,我想在很多的系統中,都有用到過吧。這已經是非常非常普通的應用功能了,所以就需要將這個功能能自定義為一個jsp標簽的話,那就肯定很方便了。所以下面就說一下,如果實現這個功能。

步驟:

(1)寫兩個Java類,其中Page,很簡單就是一個分頁對象,然后NavigationTag這個就是自定義標簽的核心映射類了(如果對於這個自定義標簽的流程不是很清楚的話,可以看看我之前寫的J2EE的知識點中的內容,都很詳細介紹了)。

Page:

package com.hnuscw.common.utils;
import java.util.List;
public class Page<T> {

private int total;
private int page;
private int size;
private List<T> rows;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}

}
Navigation:

package com.hnuscw.common.utils;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.taglibs.standard.tag.common.core.UrlSupport;

/**
* 顯示格式 上一頁 1 2 3 4 5 下一頁
*/
public class NavigationTag extends TagSupport {
static final long serialVersionUID = 2372405317744358833L;

/**
* request 中用於保存Page<E> 對象的變量名,默認為“page”
*/
private String bean = "page";

/**
* 分頁跳轉的url地址,此屬性必須
*/
private String url = null;

/**
* 顯示頁碼數量
*/
private int number = 5;

@Override
public int doStartTag() throws JspException {
JspWriter writer = pageContext.getOut();
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
Page page = (Page)request.getAttribute(bean);
if (page == null)
return SKIP_BODY;
url = resolveUrl(url, pageContext);
try {
//計算總頁數
int pageCount = page.getTotal() / page.getSize();
if (page.getTotal() % page.getSize() > 0) {
pageCount++;
}
writer.print("<nav><ul class=\"pagination\">");
//顯示“上一頁”按鈕
if (page.getPage() > 1) {
String preUrl = append(url, "page", page.getPage() - 1);
preUrl = append(preUrl, "rows", page.getSize());
writer.print("<li><a href=\"" + preUrl + "\">上一頁</a></li>");
} else {
writer.print("<li class=\"disabled\"><a href=\"#\">上一頁</a></li>");
}
//顯示當前頁碼的前2頁碼和后兩頁碼
//若1 則 1 2 3 4 5, 若2 則 1 2 3 4 5, 若3 則1 2 3 4 5,
//若4 則 2 3 4 5 6 ,若10 則 8 9 10 11 12
int indexPage = (page.getPage() - 2 > 0)? page.getPage() - 2 : 1;
for(int i=1; i <= number && indexPage <= pageCount; indexPage++, i++) {
if(indexPage == page.getPage()) {
writer.print( "<li class=\"active\"><a href=\"#\">"+indexPage+"<span class=\"sr-only\">(current)</span></a></li>");
continue;
}
String pageUrl = append(url, "page", indexPage);
pageUrl = append(pageUrl, "rows", page.getSize());
writer.print("<li><a href=\"" + pageUrl + "\">"+ indexPage +"</a></li>");
}
//顯示“下一頁”按鈕
if (page.getPage() < pageCount) {
String nextUrl = append(url, "page", page.getPage() + 1);
nextUrl = append(nextUrl, "rows", page.getSize());
writer.print("<li><a href=\"" + nextUrl + "\">下一頁</a></li>");
} else {
writer.print("<li class=\"disabled\"><a href=\"#\">下一頁</a></li>");
}
writer.print("</nav>");
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}

private String append(String url, String key, int value) {

return append(url, key, String.valueOf(value));
}

/**
* 為url 參加參數對兒
*
* @param url
* @param key
* @param value
* @return
*/
private String append(String url, String key, String value) {
if (url == null || url.trim().length() == 0) {
return "";
}

if (url.indexOf("?") == -1) {
url = url + "?" + key + "=" + value;
} else {
if(url.endsWith("?")) {
url = url + key + "=" + value;
} else {
url = url + "&" + key + "=" + value;
}
}

return url;
}

/**
* 為url 添加翻頁請求參數
*
* @param url
* @param pageContext
* @return
* @throws javax.servlet.jsp.JspException
*/
private String resolveUrl(String url, javax.servlet.jsp.PageContext pageContext) throws JspException{
//UrlSupport.resolveUrl(url, context, pageContext)
Map params = pageContext.getRequest().getParameterMap();
for (Object key:params.keySet()) {
if ("page".equals(key) || "rows".equals(key)) continue;
Object value = params.get(key);
if (value == null) continue;
if (value.getClass().isArray()) {
url = append(url, key.toString(), ((String[])value)[0]);
} else if (value instanceof String) {
url = append(url, key.toString(), value.toString());
}
}
return url;
}

/**
* @return the bean
*/
public String getBean() {
return bean;
}

/**
* @param bean the bean to set
*/
public void setBean(String bean) {
this.bean = bean;
}

/**
* @return the url
*/
public String getUrl() {
return url;
}

/**
* @param url the url to set
*/
public void setUrl(String url) {
this.url = url;
}

public void setNumber(int number) {
this.number = number;
}

}
(2)編寫自定義標簽的tld,命令為commons.tld,並且放在WEB-INF下面的tld文件下(這個文件自己創建就是了)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>2.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>common</short-name>
<uri>http://hnuscw.com/common/</uri>
<display-name>Common Tag</display-name>
<description>Common Tag library</description>

<tag>
<name>page</name>
<tag-class>com.hnuscw.common.utils.NavigationTag</tag-class>
<body-content>JSP</body-content>
<description>create navigation for paging</description>
<attribute>
<name>bean</name>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>number</name>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>url</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
(3)在jsp頁面中進行使用

引入標簽:

<%@ taglib prefix="hnuscw" uri="http://hnuscw.com/common/"%>
使用標簽:
<div class="col-md-12 text-right">
<hnuscw:page url="${pageContext.request.contextPath }/customer/list.action" />
</div>
測試實例:為了方便很多的使用,我這就還是用一個實際的例子還顯示這個效果吧。

jsp頁面:命名為:customer.jsp(當然可以不要這么多內容,自行更改即可,只是這個就相當於一個管理系統的了,所以以后只需要稍微修改就可以)

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="itcast" uri="http://itcast.cn/common/"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">

<title>客戶列表-BootCRM</title>

<!-- Bootstrap Core CSS -->
<link href="<%=basePath%>css/bootstrap.min.css" rel="stylesheet">

<!-- MetisMenu CSS -->
<link href="<%=basePath%>css/metisMenu.min.css" rel="stylesheet">

<!-- DataTables CSS -->
<link href="<%=basePath%>css/dataTables.bootstrap.css" rel="stylesheet">

<!-- Custom CSS -->
<link href="<%=basePath%>css/sb-admin-2.css" rel="stylesheet">

<!-- Custom Fonts -->
<link href="<%=basePath%>css/font-awesome.min.css" rel="stylesheet"
type="text/css">
<link href="<%=basePath%>css/boot-crm.css" rel="stylesheet"
type="text/css">

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->

</head>

<body>
<div id="wrapper">

<!-- Navigation -->
<nav class="navbar navbar-default navbar-static-top" role="navigation"
style="margin-bottom: 0">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span> <span
class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">BOOT客戶管理系統 v2.0</a>
</div>
<!-- /.navbar-header -->

<ul class="nav navbar-top-links navbar-right">
<li class="dropdown"><a class="dropdown-toggle"
data-toggle="dropdown" href="#"> <i class="fa fa-envelope fa-fw"></i>
<i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-messages">
<li><a href="#">
<div>
<strong>令狐沖</strong> <span class="pull-right text-muted">
<em>昨天</em>
</span>
</div>
<div>今天晚上向大哥找我吃飯,討論一下去梅庄的事...</div>
</a></li>
<li class="divider"></li>
<li><a class="text-center" href="#"> <strong>查看全部消息</strong>
<i class="fa fa-angle-right"></i>
</a></li>
</ul> <!-- /.dropdown-messages --></li>
<!-- /.dropdown -->
<li class="dropdown"><a class="dropdown-toggle"
data-toggle="dropdown" href="#"> <i class="fa fa-tasks fa-fw"></i>
<i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-tasks">
<li><a href="#">
<div>
<p>
<strong>任務 1</strong> <span class="pull-right text-muted">完成40%</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-success"
role="progressbar" aria-valuenow="40" aria-valuemin="0"
aria-valuemax="100" style="width: 40%">
<span class="sr-only">完成40%</span>
</div>
</div>
</div>
</a></li>
<li class="divider"></li>
<li><a href="#">
<div>
<p>
<strong>任務 2</strong> <span class="pull-right text-muted">完成20%</span>
</p>
<div class="progress progress-striped active">
<div class="progress-bar progress-bar-info" role="progressbar"
aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"
style="width: 20%">
<span class="sr-only">完成20%</span>
</div>
</div>
</div>
</a></li>
<li class="divider"></li>
<li><a class="text-center" href="#"> <strong>查看所有任務</strong>
<i class="fa fa-angle-right"></i>
</a></li>
</ul> <!-- /.dropdown-tasks --></li>
<!-- /.dropdown -->
<li class="dropdown"><a class="dropdown-toggle"
data-toggle="dropdown" href="#"> <i class="fa fa-bell fa-fw"></i>
<i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-alerts">
<li><a href="#">
<div>
<i class="fa fa-comment fa-fw"></i> 新回復 <span
class="pull-right text-muted small">4分鍾之前</span>
</div>
</a></li>
<li class="divider"></li>
<li><a href="#">
<div>
<i class="fa fa-envelope fa-fw"></i> 新消息 <span
class="pull-right text-muted small">4分鍾之前</span>
</div>
</a></li>
<li class="divider"></li>
<li><a href="#">
<div>
<i class="fa fa-tasks fa-fw"></i> 新任務 <span
class="pull-right text-muted small">4分鍾之前</span>
</div>
</a></li>
<li class="divider"></li>
<li><a href="#">
<div>
<i class="fa fa-upload fa-fw"></i> 服務器重啟 <span
class="pull-right text-muted small">4分鍾之前</span>
</div>
</a></li>
<li class="divider"></li>
<li><a class="text-center" href="#"> <strong>查看所有提醒</strong>
<i class="fa fa-angle-right"></i>
</a></li>
</ul> <!-- /.dropdown-alerts --></li>
<!-- /.dropdown -->
<li class="dropdown"><a class="dropdown-toggle"
data-toggle="dropdown" href="#"> <i class="fa fa-user fa-fw"></i>
<i class="fa fa-caret-down"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#"><i class="fa fa-user fa-fw"></i> 用戶設置</a></li>
<li><a href="#"><i class="fa fa-gear fa-fw"></i> 系統設置</a></li>
<li class="divider"></li>
<li><a href="login.html"><i class="fa fa-sign-out fa-fw"></i>
退出登錄</a></li>
</ul> <!-- /.dropdown-user --></li>
<!-- /.dropdown -->
</ul>
<!-- /.navbar-top-links -->

<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav" id="side-menu">
<li class="sidebar-search">
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="查詢內容...">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search" style="padding: 3px 0 3px 0;"></i>
</button>
</span>
</div> <!-- /input-group -->
</li>
<li><a href="customer.action" class="active"><i
class="fa fa-edit fa-fw"></i> 客戶管理</a></li>
<li><a href="salevisit.action"><i
class="fa fa-dashboard fa-fw"></i> 客戶拜訪</a></li>
</ul>
</div>
<!-- /.sidebar-collapse -->
</div>
<!-- /.navbar-static-side --> </nav>

<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">客戶管理</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="panel panel-default">
<div class="panel-body">
<form class="form-inline" action="${pageContext.request.contextPath }/customer/list.action" method="get">
<div class="form-group">
<label for="customerName">客戶名稱</label>
<input type="text" class="form-control" id="customerName" value="${custName }" name="custName">
</div>
<div class="form-group">
<label for="customerFrom">客戶來源</label>
<select class="form-control" id="customerFrom" placeholder="客戶來源" name="custSource">
<option value="">--請選擇--</option>
<c:forEach items="${fromType}" var="item">
<option value="${item.dict_id}"<c:if test="${item.dict_id == custSource}"> selected</c:if>>${item.dict_item_name }</option>
</c:forEach>
</select>
</div>
<div class="form-group">
<label for="custIndustry">所屬行業</label>
<select class="form-control" id="custIndustry" name="custIndustry">
<option value="">--請選擇--</option>
<c:forEach items="${industryType}" var="item">
<option value="${item.dict_id}"<c:if test="${item.dict_id == custIndustry}"> selected</c:if>>${item.dict_item_name }</option>
</c:forEach>
</select>
</div>
<div class="form-group">
<label for="custLevel">客戶級別</label>
<select class="form-control" id="custLevel" name="custLevel">
<option value="">--請選擇--</option>
<c:forEach items="${levelType}" var="item">
<option value="${item.dict_id}"<c:if test="${item.dict_id == custLevel}"> selected</c:if>>${item.dict_item_name }</option>
</c:forEach>
</select>
</div>
<button type="submit" class="btn btn-primary">查詢</button>
</form>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">客戶信息列表</div>
<!-- /.panel-heading -->
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>客戶名稱</th>
<th>客戶來源</th>
<th>客戶所屬行業</th>
<th>客戶級別</th>
<th>固定電話</th>
<th>手機</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${page.rows}" var="row">
<tr>
<td>${row.cust_id}</td>
<td>${row.cust_name}</td>
<td>${row.cust_source}</td>
<td>${row.cust_industry}</td>
<td>${row.cust_level}</td>
<td>${row.cust_phone}</td>
<td>${row.cust_mobile}</td>
<td>
<a href="#" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#customerEditDialog" onclick="editCustomer(${row.cust_id})">修改</a>
<a href="#" class="btn btn-danger btn-xs" onclick="deleteCustomer(${row.cust_id})">刪除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<div class="col-md-12 text-right">
<itcast:page url="${pageContext.request.contextPath }/customer/list.action" />
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
</div>
<!-- /#page-wrapper -->

</div>
<!-- 客戶編輯對話框 -->
<div class="modal fade" id="customerEditDialog" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">修改客戶信息</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" id="edit_customer_form">
<input type="hidden" id="edit_cust_id" name="cust_id"/>
<div class="form-group">
<label for="edit_customerName" class="col-sm-2 control-label">客戶名稱</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="edit_customerName" placeholder="客戶名稱" name="cust_name">
</div>
</div>
<div class="form-group">
<label for="edit_customerFrom" style="float:left;padding:7px 15px 0 27px;">客戶來源</label>
<div class="col-sm-10">
<select class="form-control" id="edit_customerFrom" placeholder="客戶來源" name="cust_source">
<option value="">--請選擇--</option>
<c:forEach items="${fromType}" var="item">
<option value="${item.dict_id}"<c:if test="${item.dict_id == custSource}"> selected</c:if>>${item.dict_item_name }</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label for="edit_custIndustry" style="float:left;padding:7px 15px 0 27px;">所屬行業</label>
<div class="col-sm-10">
<select class="form-control" id="edit_custIndustry" name="cust_industry">
<option value="">--請選擇--</option>
<c:forEach items="${industryType}" var="item">
<option value="${item.dict_id}"<c:if test="${item.dict_id == custIndustry}"> selected</c:if>>${item.dict_item_name }</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label for="edit_custLevel" style="float:left;padding:7px 15px 0 27px;">客戶級別</label>
<div class="col-sm-10">
<select class="form-control" id="edit_custLevel" name="cust_level">
<option value="">--請選擇--</option>
<c:forEach items="${levelType}" var="item">
<option value="${item.dict_id}"<c:if test="${item.dict_id == custLevel}"> selected</c:if>>${item.dict_item_name }</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label for="edit_linkMan" class="col-sm-2 control-label">聯系人</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="edit_linkMan" placeholder="聯系人" name="cust_linkman">
</div>
</div>
<div class="form-group">
<label for="edit_phone" class="col-sm-2 control-label">固定電話</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="edit_phone" placeholder="固定電話" name="cust_phone">
</div>
</div>
<div class="form-group">
<label for="edit_mobile" class="col-sm-2 control-label">移動電話</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="edit_mobile" placeholder="移動電話" name="cust_mobile">
</div>
</div>
<div class="form-group">
<label for="edit_zipcode" class="col-sm-2 control-label">郵政編碼</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="edit_zipcode" placeholder="郵政編碼" name="cust_zipcode">
</div>
</div>
<div class="form-group">
<label for="edit_address" class="col-sm-2 control-label">聯系地址</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="edit_address" placeholder="聯系地址" name="cust_address">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">關閉</button>
<button type="button" class="btn btn-primary" onclick="updateCustomer()">保存修改</button>
</div>
</div>
</div>
</div>
<!-- /#wrapper -->

<!-- jQuery -->
<script src="<%=basePath%>js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="<%=basePath%>js/bootstrap.min.js"></script>

<!-- Metis Menu Plugin JavaScript -->
<script src="<%=basePath%>js/metisMenu.min.js"></script>

<!-- DataTables JavaScript -->
<script src="<%=basePath%>js/jquery.dataTables.min.js"></script>
<script src="<%=basePath%>js/dataTables.bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="<%=basePath%>js/sb-admin-2.js"></script>

<script type="text/javascript">
function editCustomer(id) {
$.ajax({
type:"get",
url:"<%=basePath%>customer/edit.action",
data:{"id":id},
success:function(data) {
$("#edit_cust_id").val(data.cust_id);
$("#edit_customerName").val(data.cust_name);
$("#edit_customerFrom").val(data.cust_source)
$("#edit_custIndustry").val(data.cust_industry)
$("#edit_custLevel").val(data.cust_level)
$("#edit_linkMan").val(data.cust_linkman);
$("#edit_phone").val(data.cust_phone);
$("#edit_mobile").val(data.cust_mobile);
$("#edit_zipcode").val(data.cust_zipcode);
$("#edit_address").val(data.cust_address);

}
});
}
function updateCustomer() {
$.post("<%=basePath%>customer/update.action",$("#edit_customer_form").serialize(),function(data){
alert("客戶信息更新成功!");
window.location.reload();
});
}

function deleteCustomer(id) {
if(confirm('確實要刪除該客戶嗎?')) {
$.post("<%=basePath%>customer/delete.action",{"id":id},function(data){
alert("客戶刪除更新成功!");
window.location.reload();
});
}
}
</script>

</body>

</html>
pojo實體:

customer類代碼:(也就是頁面中顯示的每條數據內容的javabean)

package com.hnuscw.crm.pojo;

import java.util.Date;

public class Customer {
private Long cust_id;
private String cust_name;
private Long cust_user_id;
private Long cust_create_id;
private String cust_source;
private String cust_industry;
private String cust_level;
private String cust_linkman;
private String cust_phone;
private String cust_mobile;
private String cust_zipcode;
private String cust_address;
private Date cust_createtime;
public Long getCust_id() {
return cust_id;
}
public void setCust_id(Long cust_id) {
this.cust_id = cust_id;
}
public String getCust_name() {
return cust_name;
}
public void setCust_name(String cust_name) {
this.cust_name = cust_name;
}
public Long getCust_user_id() {
return cust_user_id;
}
public void setCust_user_id(Long cust_user_id) {
this.cust_user_id = cust_user_id;
}
public Long getCust_create_id() {
return cust_create_id;
}
public void setCust_create_id(Long cust_create_id) {
this.cust_create_id = cust_create_id;
}
public String getCust_source() {
return cust_source;
}
public void setCust_source(String cust_source) {
this.cust_source = cust_source;
}
public String getCust_industry() {
return cust_industry;
}
public void setCust_industry(String cust_industry) {
this.cust_industry = cust_industry;
}
public String getCust_level() {
return cust_level;
}
public void setCust_level(String cust_level) {
this.cust_level = cust_level;
}
public String getCust_linkman() {
return cust_linkman;
}
public void setCust_linkman(String cust_linkman) {
this.cust_linkman = cust_linkman;
}
public String getCust_phone() {
return cust_phone;
}
public void setCust_phone(String cust_phone) {
this.cust_phone = cust_phone;
}
public String getCust_mobile() {
return cust_mobile;
}
public void setCust_mobile(String cust_mobile) {
this.cust_mobile = cust_mobile;
}
public String getCust_zipcode() {
return cust_zipcode;
}
public void setCust_zipcode(String cust_zipcode) {
this.cust_zipcode = cust_zipcode;
}
public String getCust_address() {
return cust_address;
}
public void setCust_address(String cust_address) {
this.cust_address = cust_address;
}
public Date getCust_createtime() {
return cust_createtime;
}
public void setCust_createtime(Date cust_createtime) {
this.cust_createtime = cust_createtime;
}
}
Queryvo類代碼:(這個主要就是對於封裝分頁處理和搜索查詢來的)

package com.hnuscw.crm.pojo;
public class QueryVo {

//客戶名稱
private String custName;
private String custSource;
private String custIndustry;
private String custLevel;
//當前頁
private Integer page;
//每頁數
private Integer size = 10;
//開始行
private Integer startRow = 0;


public Integer getStartRow() {
return startRow;
}
public void setStartRow(Integer startRow) {
this.startRow = startRow;
}
//
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getCustSource() {
return custSource;
}
public void setCustSource(String custSource) {
this.custSource = custSource;
}
public String getCustIndustry() {
return custIndustry;
}
public void setCustIndustry(String custIndustry) {
this.custIndustry = custIndustry;
}
public String getCustLevel() {
return custLevel;
}
public void setCustLevel(String custLevel) {
this.custLevel = custLevel;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
}
contraoller層:

//入口
@RequestMapping(value = "/customer/list")
public String list(QueryVo vo,Model model){
//因為很多頁面中都有搜索內容的處理,所以下面也進行了一點內容的添加,這個可以根據需要進行
List<BaseDict> fromType = baseDictService.selectBaseDictListByCode("002");//這是為了頁面進行搜索選擇而增加
List<BaseDict> industryType = baseDictService.selectBaseDictListByCode("001");//為了頁面搜索選擇而增加
List<BaseDict> levelType = baseDictService.selectBaseDictListByCode("006");//為了頁面搜索選擇而增加
model.addAttribute("fromType", fromType);
model.addAttribute("industryType", industryType);
model.addAttribute("levelType", levelType);

//通過四個條件 查詢分頁對象(這是分頁處理的核心的核心)
Page<Customer> page = customerService.selectPageByQueryVo(vo);
model.addAttribute("page", page);
model.addAttribute("custName", vo.getCustName()); //下面幾句話都是為了jsp回顯而已
model.addAttribute("custSource", vo.getCustSource());
model.addAttribute("custIndustry", vo.getCustIndustry());
model.addAttribute("custLevel", vo.getCustLevel());

return "customer";// 返回到上面的那個jsp主界面
}
service接口層:(這里幾個都貼出來吧,其實關於分頁的主要就是CuestomerService)

搜索條件的service:

package com.hnuscw.crm.service;
import java.util.List;
import com.itheima.crm.pojo.BaseDict;
public interface BaseDictService {
//查詢
public List<BaseDict> selectBaseDictListByCode(String code);
}
customer分頁對象的service:

package com.hnu.scw.service;
import com.itheima.crm.pojo.Customer;
import com.itheima.crm.pojo.QueryVo;
public interface CustomerService {
// 通過四個條件 查詢分頁對象
public Page<Customer> selectPageByQueryVo(QueryVo vo);
}
service實現層:

搜索條件的實現層代碼:

package com.hnuscw.crm.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itheima.crm.mapper.BaseDictDao;
import com.itheima.crm.pojo.BaseDict;

@Service
//@Transactional
public class BaseDictServiceImpl implements BaseDictService {
@Autowired
private BaseDictDao baseDictDao;

public List<BaseDict> selectBaseDictListByCode(String code) {
// TODO Auto-generated method stub
return baseDictDao.selectBaseDictListByCode(code);
}
}
分頁處理的實現層代碼:

package com.itheima.crm.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itheima.common.utils.Page;
import com.itheima.crm.mapper.CustomerDao;
import com.itheima.crm.pojo.Customer;
import com.itheima.crm.pojo.QueryVo;

/**
* 客戶管理
*
* @author lx
*
*/
@Service
public class CustomerServiceImpl implements CustomerService {

@Autowired
private CustomerDao customerDao;
// 通過四個條件 查詢分頁對象
public Page<Customer> selectPageByQueryVo(QueryVo vo) {
Page<Customer> page = new Page<Customer>();
//每頁數
page.setSize(5);
vo.setSize(5);
if (null != vo) {
// 判斷當前頁
if (null != vo.getPage()) {
page.setPage(vo.getPage());
vo.setStartRow((vo.getPage() -1)*vo.getSize());
}
if(null != vo.getCustName() && !"".equals(vo.getCustName().trim())){
vo.setCustName(vo.getCustName().trim());
}
if(null != vo.getCustSource() && !"".equals(vo.getCustSource().trim())){
vo.setCustSource(vo.getCustSource().trim());
}
if(null != vo.getCustIndustry() && !"".equals(vo.getCustIndustry().trim())){
vo.setCustIndustry(vo.getCustIndustry().trim());
}
if(null != vo.getCustLevel() && !"".equals(vo.getCustLevel().trim())){
vo.setCustLevel(vo.getCustLevel().trim());
}
//總條數
page.setTotal(customerDao.customerCountByQueryVo(vo));
page.setRows(customerDao.selectCustomerListByQueryVo(vo));
}
return page;
}
}
dao層接口:

搜索處理的dao層:

package com.hnuscw.crm.mapper;
import java.util.List;
import com.itheima.crm.pojo.BaseDict;
public interface BaseDictDao {
//查詢
public List<BaseDict> selectBaseDictListByCode(String code);
}
分頁處理的dao層:
package com.itheima.crm.mapper;

import java.util.List;

import com.itheima.crm.pojo.Customer;
import com.itheima.crm.pojo.QueryVo;

public interface CustomerDao {
//總條數
public Integer customerCountByQueryVo(QueryVo vo);
//結果集
public List<Customer> selectCustomerListByQueryVo(QueryVo vo);

}
mapper映射:

搜索處理的映射mapper:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.crm.mapper.BaseDictDao">
<!-- 查詢 -->
<select id="selectBaseDictListByCode" parameterType="String" resultType="BaseDict">
select * from base_dict where dict_type_code = #{value}
</select>

</mapper>
分頁處理的映射mapper:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.crm.mapper.CustomerDao">
<!-- //總條數 -->
<!-- public Integer customerCountByQueryVo(QueryVo vo); private String custName;
private String custSource; private String custIndustry; private String custLevel; -->
<select id="customerCountByQueryVo" parameterType="QueryVo"
resultType="Integer">
select count(1) from customer
<where>
<if test="custName != null and custName != ''">
cust_name like "%"#{custName}"%"
</if>
<if test="custSource != null and custSource != ''">
and cust_source = #{custSource}
</if>
<if test="custIndustry != null and custIndustry != ''">
and cust_industry = #{custIndustry}
</if>
<if test="custLevel != null and custLevel != ''">
and cust_level = #{custLevel}
</if>
</where>
</select>
<!-- //結果集 -->
<!-- public List<Customer> selectCustomerListByQueryVo(QueryVo vo); -->
<select id="selectCustomerListByQueryVo" parameterType="QueryVo"
resultType="Customer">
select * from customer
<where>
<if test="custName != null and custName != ''">
cust_name like "%"#{custName}"%"
</if>
<if test="custSource != null and custSource != ''">
and cust_source = #{custSource}
</if>
<if test="custIndustry != null and custIndustry != ''">
and cust_industry = #{custIndustry}
</if>
<if test="custLevel != null and custLevel != ''">
and cust_level = #{custLevel}
</if>
</where>
limit #{startRow},#{size}
</select>
</mapper>
PS:(1)上面的代碼加上對自定義標簽的使用的話,就實現了分頁內容的處理了,所以,如果需要使用的話就可以根據這樣的內容進行處理即可。此外,上面的jsp中是有條件搜索的,所以代碼中也加入了對條件搜索的處理,如果你那界面只是想實現分頁處理的話,那么在每個層次中將條件處理的代碼刪除即可,這樣也不會進行影響,關鍵還是要看懂代碼,如果看懂了的話,還是很好進行處理的。當然,這並不是最優化的情況,還能夠進行處理,只是這是一種方法而已。

(2)如果要使用上面的jsp代碼的話, 要先配置一下下面的內容,對內容進行放行處理.

實現方法二:通過JSP控制分頁處理的方法
   分析:在第二點中提到了分頁的方法,主要是利用jstl中的自定義標簽來實現的,接下來的話,介紹一下另外一種方法,就是如何利用jsp頁面來控制分頁的處理方法。

步驟:(1)編寫jsp中的分頁內容代碼(這里主要就是寫一下分頁的頁面界面和當頁數過多的時候如何進行處理的問題)

<!-- 分頁內容的處理部分 -->
<td style="vertical-align:top;">
<div class="pagination" style="float: right;padding-top: 0px;margin-top: 0px;">
<ul>
<li><a>共<font color=red>${page.totalResult}</font>條</a></li>
<li><input type="number" value="" id="jumpPageNumber" style="width:50px;text-align:center;float:left" placeholder="頁碼"/></li>
<li style="cursor:pointer;"><a onclick="jumpPage();" class="btn btn-mini btn-success">跳轉</a></li>
<c:choose>
<c:when test="${page.currentPage == 1 }">
<li><a>首頁</a></li>
<li><a>上頁</a></li>
<!-- 分是否為第一頁的兩種情況,不為第一頁的話,那么就要設置首頁和上一頁為有onclick點擊事件 -->
</c:when>
<c:otherwise>
<li style="cursor:pointer;"><a onclick="nextPage(1);">首頁</a></li>
<li style="cursor:pointer;"><a onclick="nextPage(${page.currentPage}-1);">上頁</a></li>
</c:otherwise>
</c:choose>
<!-- 分頁處理的優化工作 -->
<c:choose>
<c:when test="${page.currentPage + 4 > page.totalPage}"> <!-- 現在每個分頁為顯示5頁 ,所以先判斷當前的頁面+4是否大於總的頁面數-->
<c:choose>
<c:when test="${page.totalPage-4 > 0}"> <!-- 判斷是否總的頁面數也是大於5,因為這樣的話,就會出現兩種情況 -->
<c:forEach var="index1" begin="${page.totalPage-4}" end="${page.totalPage}" step="1">
<c:if test="${index1 >= 1}">
<c:choose>
<c:when test="${page.currentPage == index1}">
<li><a><b style="color: red;">${page.currentPage}</b></a></li>
</c:when>
<c:otherwise>
<li style="cursor:pointer;"><a onclick="changePage(${index1});">${index1}</a></li>
</c:otherwise>
</c:choose>
</c:if>
</c:forEach>
</c:when>

<c:otherwise> <!-- 當總的頁面數都不足5的時候,那么直接全部顯示即可,不需要考慮太多 -->
<c:forEach var="pagenumber" begin="1" end="${page.totalPage}">
<!-- 判斷頁碼是否是當前頁,是的話,就換個顏色來標記 -->
<c:choose>
<c:when test="${page.currentPage == pagenumber}">
<li><a><b style="color: red;">${page.currentPage}</b></a></li>
</c:when>
<c:otherwise>
<li style="cursor:pointer;"><a onclick="changePage(${pagenumber});">${pagenumber}</a></li>
</c:otherwise>
</c:choose>
</c:forEach>
</c:otherwise>
</c:choose>

</c:when>

<c:otherwise> <!-- 當當前頁面數+4都還是小於總的頁面數的情況 -->
<c:choose>
<c:when test="${page.currentPage != 1}"> <!-- 判斷當前頁面是否就是第一頁,因為這樣也會有兩種情況的處理 -->
<c:forEach var="index2" begin="${page.currentPage-1}" end="${page.currentPage+3}"> <!-- 從當前頁面減一的頁面數開始,這樣點擊前面一頁就會顯示其他的頁面,從而實現頁面跳轉 -->
<c:choose>
<c:when test="${page.currentPage == index2}">
<li><a><b style="color: red;">${page.currentPage}</b></a></li>
</c:when>
<c:otherwise>
<li style="cursor:pointer;"><a onclick="changePage(${index2});">${index2}</a></li>
</c:otherwise>
</c:choose>
</c:forEach>
</c:when>

<c:otherwise> <!-- 當當前頁面數就是第一頁的時候,就直接顯示1-5頁即可 -->
<c:forEach var="index3" begin="1" end="5">
<c:choose>
<c:when test="${page.currentPage == index3}">
<li><a><b style="color: red;">${page.currentPage}</b></a></li>
</c:when>
<c:otherwise>
<li style="cursor:pointer;"><a onclick="changePage(${index3});">${index3}</a></li>
</c:otherwise>
</c:choose>
</c:forEach>
</c:otherwise>
</c:choose>
</c:otherwise>
</c:choose>
<!-- 處理 當前頁是否最后一頁,不是的話,就需要添加下一頁的點擊時間-->
<c:choose>
<c:when test="${page.currentPage == page.totalPage }">
<li><a>下頁</a></li>
<li><a>尾頁</a></li>
</c:when>
<c:otherwise>
<li style="cursor:pointer;"><a onclick="nextPage(${page.currentPage}+1)">下頁</a></li>
<li style="cursor:pointer;"><a onclick="nextPage(${page.totalPage});">尾頁</a></li>
</c:otherwise>
</c:choose>

<!-- 處理 頁面大小的處理-->
<li><a>第${page.currentPage}頁</a></li>
<li><a>共${page.totalPage}頁</a></li>
<!-- 進行每一個頁面顯示數據條目大小的選擇 -->
<li>
<!-- 注意:當進行選擇改變的時候,就會出發changeCount這個事件,再通過Ajax進行頁面數據的請求 -->
<select title='顯示條數' style="width:55px;float:left;" onchange="changeCount(this.value)">
<option value="${page.showCount}">${page.showCount}</option>
<option value='5'>5</option>
<option value='10'>10</option>
<option value='20'>20</option>
<option value='30'>30</option>
<option value='40'>40</option>
<option value='50'>50</option>
<option value='60'>60</option>
<option value='70'>70</option>
</select>
</li>
</ul>
</div>
</td>
備注:1:上面是放在一個table標簽中的,所以是用td標簽來進行標識
   2:這里默認的處理是每一個分頁是分5頁內容,如果需要進行變化的話,那么自己進行修改相對應的注釋中的內容即可

(2)jsp中的JS代碼(用於控制點擊頁面的跳轉處理)

//下面都是分頁處理的操作
//(1)操作1:點擊頁碼進行顯示數據
function changePage(clickpage){
//注意點:
//(1)這里用ajax進行處理的話會存在問題,因為ajax無法進行頁面跳轉,所以如果用ajax的話,那么就要回到這個success中進行拼接內容,感覺有點麻煩了。
//(2)獲取搜索框中是否有內容
var retrieve_content = $('#retrieve_content').val();
//(3)直接重定向帶參數過去,currentPage表示將要顯示的頁面,showCount表示為每頁的數據條數
window.location = "${pageContext.request.contextPath}/asset/asystem_showapprover?currentPage="+clickpage+"&showCount="+${page.showCount}+"&retrieve_content="+ encodeURI(encodeURI(retrieve_content));
/* $.ajax({
url:'${pageContext.request.contextPath}/asset/asystem_showapprover',
data:{"currentPage":clickpage},
async:true,
type:"POST",
success:function(data){

},
error:function(){
alert("切換失敗!請稍后重試!");
},
dataType:"json"
}); */
}
//操作2:點擊上下頁,進行頁碼內容的改變
function nextPage(clickpage){
//(1)獲取搜索框中是否有內容
var retrieve_content = $('#retrieve_content').val(); //后面要注意編碼,因為如果是中文的話,這樣傳會發生亂碼的,那么搜索肯定就匹配不到內容
window.location = "${pageContext.request.contextPath}/asset/asystem_showapprover?currentPage="+clickpage+"&showCount="+${page.showCount}+"&retrieve_content="+ encodeURI(encodeURI(retrieve_content));
}
//操作3:選擇下拉框的時候,進行頁面大小的改變
function changeCount(pagesize){
//(1)獲取搜索框中是否有內容
var retrieve_content = $('#retrieve_content').val(); //后面要注意編碼,因為如果是中文的話,這樣傳會發生亂碼的,那么搜索肯定就匹配不到內容
window.location = "${pageContext.request.contextPath}/asset/asystem_showapprover?currentPage="+${page.currentPage}+"&showCount="+pagesize+"&retrieve_content="+ encodeURI(encodeURI(retrieve_content));
}
//操作4:處理跳轉按鈕頁面的處理
function jumpPage(){
//1.獲取頁碼框中的數值大小
var toPaggeVlue = $('#jumpPageNumber').val();
//2.對數值進行一些判斷,是否符合正常的規范
if(toPaggeVlue == ''){ //如果是空,就設置為1
$('#jumpPageNumber').val(1);
toPaggeVlue =1;
}
if(isNaN(Number(toPaggeVlue))){ //如果是非數字,也就設置為1,其實這個在input組件中,已經可以控制了
$('#jumpPageNumber').val(1);
toPaggeVlue =1;
}
//3:執行nextPage函數就可以了
nextPage(toPaggeVlue);
}
備注:這里就是簡單的JS跳轉控制的代碼了

(3)PgaeOption自定義分頁處理的對象(主要就是用於管理分頁的內容)

package com.mbfw.entity.assets;
import com.mbfw.util.PageData;
public class PageOption {
private int showCount; // 每頁顯示記錄數
private int totalPage; // 總頁數
private int totalResult; // 總記錄數
private int currentPage; // 當前頁
private int currentResult; // 當前記錄起始索引
private PageData pd ; //封裝一個PageData對象,主要是為了能夠方便進行檢索功能

public PageData getPd() {
return pd;
}

public void setPd(PageData pd) {
this.pd = pd;
}

public PageOption(int showCount , int currentPage){
this.showCount = showCount;
this.currentPage = currentPage;
}

public int getShowCount() {
return showCount;
}

public void setShowCount(int showCount) {
this.showCount = showCount;
}

public int getTotalPage() {
if (totalResult % showCount == 0)
totalPage = totalResult / showCount;
else
totalPage = totalResult / showCount + 1;
return totalPage;
}

public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}

public int getTotalResult() {
return totalResult;
}

public void setTotalResult(int totalResult) {
this.totalResult = totalResult;
}

public int getCurrentPage() {
if (currentPage <= 0)
currentPage = 1;
if (currentPage > getTotalPage())
currentPage = getTotalPage();
return currentPage;
}

public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}

//獲取當前頁的數據條的索引
public int getCurrentResult() {
currentResult = (getCurrentPage() - 1) * getShowCount();
if (currentResult < 0)
currentResult = 0;
return currentResult;
}


public void setCurrentResult(int currentResult) {
this.currentResult = currentResult;
}


}
備注:其中做了一些頁面數目的控制的管理,大家應該一看就能夠明白含義的。當然,這些控制在controller層或者service層進行管理都可以的哦!!!

(4)controller層代碼

@Autowired
private AssetApproverManageService ams;

//點擊審核人員,進行顯示所有審核人員信息
@RequestMapping(value="/asystem_showapprover")
public ModelAndView showApproverInfo() throws Exception{
ModelAndView mav = this.getModelAndView();
PageData pd = this.getPageData();
List<PageData> listApprover = new ArrayList<PageData>();

PageOption page = new PageOption(5, 1); //默認初始化一進來顯示就是每頁顯示5條,當前頁面為1
//(1)獲取是否有傳過來需要顯示的頁面數,如果有,就設置相應的屬性
if(pd.getString("currentPage") != null){
page.setCurrentPage(Integer.parseInt(pd.getString("currentPage")));
}
//(2)獲取是否有傳過來每個頁面顯示的條數,如果有,就設置相應的屬性
if(pd.getString("showCount") != null){
page.setShowCount(Integer.parseInt(pd.getString("showCount")));
}
//------沒有進行檢索的處理-----
if(pd.getString("retrieve_content") == null || pd.getString("retrieve_content") == ""){
//(3)查詢數據庫中數據的總條數
Integer totalnumber = ams.findTotalDataNumber();
//(4)設置總的數據條數
page.setTotalResult(totalnumber);
//(5)設置需要顯示的數據的索引,其實這有個公式就是為了分頁查詢limit (currentPage-1)*showcount,showcount即可
page.setCurrentResult((page.getCurrentPage()-1)*(page.getShowCount()));
//(6)查詢數據庫,返回對應條數的數據
listApprover = ams.listPdPageApprover(page);
}
//--------進行檢索處理
else{
//(3)獲取傳送過來的進行檢索的內容(這里要解碼,因為如果是中文的話就會發生亂碼問題)
pd.put("retrieve_content", URLDecoder.decode(pd.getString("retrieve_content"), "utf-8"));
//(4)設置分頁中需要進行檢索的姓名的內容,便於在分頁中根據姓名獲取內容
page.setPd(pd);
//(5)查詢對應審核人員姓名的數據總條數
Integer totalnumber = ams.findNumberBySearchName(page);
//(6)設置總的數據條數
page.setTotalResult(totalnumber);
//(7)設置需要顯示的數據的索引
page.setCurrentResult((page.getCurrentPage()-1)*(page.getShowCount()));
//(8)查詢數據庫,返回對應檢索姓名的數據
listApprover = ams.listSearchNameApprover(page);
}

mav.addObject("listApprover",listApprover); //返回對應條數的數據
mav.addObject("page",page); //返回對應的分頁的內容
mav.addObject("deleteresult",pd.getString("delresult"));//返回批量刪除操作后的結果
mav.addObject("addresult",pd.getString("addresult"));//返回添加審核人員操作后的結果
mav.setViewName("system/asystem_set/asystem_approver_list");
return mav;
}
備注:我這里用了自定義的PageDate對象,如果要用springmvc中的話,就用Model對象就可以了,只是用來返回數據到JSP中而已的。。。因為分頁大部分是用於在顯示數據的頁面中的,所以我這里也是處理顯示數據的用途的controller。。另外,我這里面還加入了檢索的管理,對於這個部分可以忽略。
(5)service層代碼

1:獲取數據的總條數

public Integer findTotalDataNumber() throws Exception {
return (Integer) dao.findForObject("ApproverManage.findTotalNumber", null);
}
2:獲取對應的分頁的內容數據

public List<PageData> listPdPageApprover(PageOption page) throws Exception{
return (List<PageData>) dao.findForList("ApproverManage.approverListPage" ,page);
}
(6)mybatis層的mapper代碼

1:獲取數據的總條數(這個隨便寫,根據自己的需要進行的是查詢哪個數據庫中的表即可,我這寫的只是一個測試例子,告訴你們怎么寫格式)

<select id="findTotalNumber" resultType="Integer">
select count(*)
from
sys_approver
</select>
2:獲取分頁數據的內容

<select id="approverListPage" parameterType="com.mbfw.entity.assets.PageOption" resultType="pd" useCache="false">
select *
from sys_approver
limit #{currentResult},#{showCount}
</select>
備注:mybatis中的這代碼,主要就是告訴大家怎么用的而已,具體的查詢哪個表還是根據自己的需要進行替換即可。簡單點說,就是查詢數據總條數和對應分頁中的數據內容即可。。。很容易理解的

總結:針對上面的兩種方法,大家可以根據需要進行選擇,如果喜歡在JSP控制,就用第二種方法,如果喜歡在service層控制就用第一種即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM