日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java 分页查询_JavaWeb之分页查询

發布時間:2023/12/10 java 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 分页查询_JavaWeb之分页查询 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

時間:2016-12-11 01:41

1、分頁的優點:

只查詢一頁,不需要查詢所有數據,能夠提高效率。

2、分頁數據

頁面的數據都是由Servlet傳遞的

* ? 當前頁:pageCode

> ? 如果頁面沒有向Servlet傳遞頁碼,那么Servlet默認為第一頁,否則按照傳遞頁碼為準。

* ? 總頁數:totalPages

> ? 總記錄數 / 每頁記錄數

* ? 總記錄數:totalRecord

> ? Dao來獲取,select count(*) from customer

* ? 每頁記錄數:稱為業務數據或系統數據。

* ? 當前頁數據:beanList

* ? URL

3、數據的傳遞

這些分頁數據總要在各層之間來回傳遞,可以把這些分頁數據封裝到一個JavaBean中,它就叫分頁Bean,例如:PageBean。

import java.util.List;

public class PageBean {

// 當前頁碼pageCode

private int pageCode;

/*

* 總頁數

* 通過計算得出,不允許外界設置值

* 因為只能get,所以不需要成員變量,通過計算即可得出

*/

// private int totalPages;

// 總記錄數

private int totalRecord;

// 每頁記錄數

private int pageSize;

// 當前頁的記錄

private List beanList;

public int getPageCode() {

return pageCode;

}

public void setPageCode(int pageCode) {

this.pageCode = pageCode;

}

public int getTotalPages() {

/*

* 計算總頁數

* 通過總記錄數和每頁記錄數來計算總頁數,當存在余數時,總頁數 + 1

*/

int totalPages = totalRecord / pageSize;

return totalRecord % pageSize == 0 ? totalPages : totalPages + 1;

}

// public void setTotalPages(int totalPages) {

// this.totalPages = totalPages;

// }

public int getTotalRecord() {

return totalRecord;

}

public void setTotalRecord(int totalRecord) {

this.totalRecord = totalRecord;

}

public int getPageSize() {

return pageSize;

}

public void setPageSize(int pageSize) {

this.pageSize = pageSize;

}

public List getBeanList() {

return beanList;

}

public void setBeanList(List beanList) {

this.beanList = beanList;

}

@Override

public String toString() {

return "PageBean [pageCode=" + pageCode + ", totalPages=" + ", totalRecord=" + totalRecord + ", pageSize=" + pageSize + ", beanList=" + beanList + "]";

}

public PageBean(int pageCode, int totalRecord, int pageSize,?List beanList) {

super();

this.pageCode = pageCode;

this.totalRecord = totalRecord;

this.pageSize = pageSize;

this.beanList = beanList;

}

public PageBean() {

super();

}

}

4、分頁在各層中的處理

* ? 頁面:給出分頁相關的鏈接。

> ? 頁面需要給Servlet傳遞當前頁碼。

* ? Servlet:創建PageBean對象, 給PageBean對象所有的屬性賦值,然后傳遞給頁面。

> ? 給Dao傳遞當前頁碼和每頁記錄數。

* ? Service:略

* ? Dao

> ? 負責獲取:totalRecord,select count(*) from customer

> ? 負責獲取:BeanList,select * from customer limit x, y,從x行開始,查詢y行。

> ? limit計算公式:(當前頁-1) * 每頁記錄數,得出的就是起始行

5、顯示分頁頁碼列表

1 2 3 4 5 6 7 8 9 10

* ? 最多顯示多少個頁碼?

> ? 暫定10個

* ? 當前頁在頁碼列表中的位置?

> ? 暫定為6

只需要pageCode就可以完成頁碼列表,需要使用pageCode來推算出起始頁碼(begin)和結束頁碼(end)

計算公式:

* ? 如果總頁數 <= 10(列表長度),那么begin = 1,end = 總頁數

* ? 如果總頁數 > 10,使用公式計算

> ? begin = pageCode - 5

> ? end = pageCode + 4

> ? begin溢出:當begin小于1時,讓begin = 1

> ? end溢出:當end > totalPages時,讓end = totalPages

6、在超鏈接中保留請求參數

當使用多條件查詢時,如果點擊其它超鏈接,會丟失原超鏈接中的參數,也就是丟失請求條件,所以需要在頁面的所有超鏈接中都要保留參數。

可以把?后的全部參數用一個字符串保存到PageBean的URL屬性中,這個任務交給Servlet。

然后在頁面中使用${pageBean.url }來設置超鏈接。

——項目代碼

===============================================================================

com.wyc.cstm.dao.CustomerDao

import java.util.ArrayList;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;

import org.apache.commons.dbutils.handlers.BeanListHandler;

import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.wyc.cstm.domain.Customer;

import com.wyc.cstm.domain.PageBean;

import com.wyc.jdbc.TxQueryRunner;

/**

* 持久層 通過QueryRunner來操作數據庫

*

* @author 31067

*

*/

public class CustomerDao {

private QueryRunner qr = new TxQueryRunner();

// /*

// * 查詢全部客戶信息

// */

// public List findAll() {

// try {

// String sql = "select * from customer";

// return qr.query(sql, new BeanListHandler(Customer.class));

// } catch (Exception e) {

// throw new RuntimeException(e);

// }

// }

public PageBean findAll(int pageCode, int pageSize) {

try {

/*

* 1、創建PageBean對象 2、設置PageBean對象的pageCode和pageSize

* 3、得到totalRecord,設置給pageBean 4、得到beanList,設置給pageBean 5、返回pageBean

*/

PageBean pageBean = new PageBean();

/*

* 設置pageCode、pageSize

*/

pageBean.setPageCode(pageCode);

pageBean.setPageSize(pageSize);

/*

* 得到totalRecord

*/

String sql = "select count(*) from customer";

// 返回值類型是Object,強轉為Number類型

Number num = (Number) qr.query(sql, new ScalarHandler());

int totalRecord = num.intValue();

pageBean.setTotalRecord(totalRecord);

/*

* 得到beanList

*/

sql = "select * from customer order by cname limit ?, ?";

// (當前頁碼 - 1) * 每行記錄數 = 起始行

Object[] params = { (pageCode - 1) * pageSize, pageSize };

List beanList = qr.query(sql, new BeanListHandler(Customer.class), params);

pageBean.setBeanList(beanList);

return pageBean;

} catch (Exception e) {

throw new RuntimeException(e);

}

}

/**

* 多條件組合查詢

*

* @param criteria

* @return

*/

// public List query(Customer criteria) {

// /*

// * 1、給出SQL模板

// * 2、給出參數

// * 3、調用query()方法

// * 結果集處理器:BeanListHandler

// */

//

// // 給出SQL語句的前半部分

// StringBuilder sql = new

// StringBuilder("select * from customer where 1 = 1");

// /*

// * 1、判斷條件,向SQL語句中追加where子句

// * 因為不能確定是否包含該參數,所以需要使用if語句來判斷

// * 2、給出參數

// * 因為不能確定?占位符所對應的參數,所以在判斷參數時,就要添加參數

// * 使用ArrayList來裝載參數

// */

//

// // 裝載參數

// List params = new ArrayList();

//

//

// String cname = criteria.getCname();

// if(cname != null && !cname.trim().isEmpty())

// {

// sql.append(" and cname = ?");

// //模糊查詢

// params.add("%" + cname + "%");

// }

//

// String gender = criteria.getGender();

// if(gender != null && !gender.trim().isEmpty())

// {

// sql.append(" and gender = ?");

// params.add(gender);

// }

//

// String cellphone = criteria.getCellphone();

// if(cellphone != null && !cellphone.trim().isEmpty())

// {

// sql.append(" and cellphone = ?");

// params.add("%" + cellphone + "%");

// }

//

// String email = criteria.getEmail();

// if(email != null && !email.trim().isEmpty())

// {

// sql.append(" and email = ?");

// params.add("%" + email + "%");

// }

//

// /*

// * 執行query

// */

// try {

// return qr.query(sql.toString(), new

// BeanListHandler(Customer.class), params.toArray());

// } catch (SQLException e) {

// throw new RuntimeException(e);

// }

// }

public PageBean query(Customer criteria, int pageCode, int pageSize) {

try {

/*

* 1、創建PageBean對象 2、設置已有屬性,pageCode和pageSize 3、得到totalRecord

* 4、得到BeanList

*/

/*

* 創建PageBean對象,設置已有屬性

*/

PageBean pageBean = new PageBean();

pageBean.setPageCode(pageCode);

pageBean.setPageSize(pageSize);

/*

* 得到tr,需要根據條件進行查詢

*/

// 給出SQL語句的前半部分

StringBuilder countSql = new StringBuilder("select count(*) from customer");

StringBuilder whereSql = new StringBuilder(" where 1 = 1");

/*

* 1、判斷條件,向SQL語句中追加where子句 因為不能確定是否包含該參數,所以需要使用if語句來判斷 2、給出參數

* 因為不能確定?占位符所對應的參數,所以在判斷參數時,就要添加參數 使用ArrayList來裝載參數

*/

// 裝載參數

List params = new ArrayList();

String cname = criteria.getCname();

if (cname != null && !cname.trim().isEmpty()) {

whereSql.append(" and cname like ?");

// 模糊查詢

params.add("%" + cname + "%");

}

String gender = criteria.getGender();

if (gender != null && !gender.trim().isEmpty()) {

whereSql.append(" and gender = ?");

params.add(gender);

}

String cellphone = criteria.getCellphone();

if (cellphone != null && !cellphone.trim().isEmpty()) {

whereSql.append(" and cellphone like ?");

params.add("%" + cellphone + "%");

}

String email = criteria.getEmail();

if (email != null && !email.trim().isEmpty()) {

whereSql.append(" and email like ?");

params.add("%" + email + "%");

}

/*

* 執行SQL語句 select count(*) from customer = where ....

*/

Number num = (Number) qr.query(countSql.append(whereSql).toString(), new ScalarHandler(), params.toArray());

int totalRecord = num.intValue();

pageBean.setTotalRecord(totalRecord);

/*

* 得到beanList

*/

StringBuilder sql = new StringBuilder("select * from customer");

/*

* 查詢beanList這一步還需要給出limit子句

*/

StringBuilder limitSql = new StringBuilder(" limit ?,?");

/*

* params中需要給出limit后對應的參數值

*/

params.add((pageCode - 1) * pageSize);

params.add(pageSize);

List beanList = qr.query(sql.append(whereSql).append(limitSql).toString(), new BeanListHandler(Customer.class), params.toArray());

pageBean.setBeanList(beanList);

return pageBean;

} catch (Exception e) {

throw new RuntimeException(e);

}

}

}

===============================================================================

com.wyc.cstm.domain.Customer

/**

* 領域對象

* 與表單和數據庫表對應

*/

public class Customer {

/*

* 對應數據庫表:

* cid CHAR(32) PRIMARY KEY,

* cname VARCHAR(40) NOT NULL,

* gender VARCHAR(6) NOT NULL,

* birthday CHAR(10),

* cellphone VARCHAR(15),

* email VARCHAR(40),

* description VARCHAR(500)

*/

private String cid;//主鍵

private String cname;//客戶姓名

private String gender;//性別

private String birthday;//客戶生日

private String cellphone;//客戶手機

private String email;//客戶郵箱

private String description;//客戶信息描述

public String getCid() {

return cid;

}

public void setCid(String cid) {

this.cid = cid;

}

public String getCname() {

return cname;

}

public void setCname(String cname) {

this.cname = cname;

}

public String getGender() {

return gender;

}

public void setGender(String gender) {

this.gender = gender;

}

public String getBirthday() {

return birthday;

}

public void setBirthday(String birthday) {

this.birthday = birthday;

}

public String getCellphone() {

return cellphone;

}

public void setCellphone(String cellphone) {

this.cellphone = cellphone;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getDescription() {

return description;

}

public void setDescription(String description) {

this.description = description;

}

@Override

public String toString() {

return "Customer [cid=" + cid + ", cname=" + cname + ", gender=" + gender + ", birthday=" + birthday + ", cellphone=" + cellphone + ", email=" + email + ", description="?+ description + "]";

}

public Customer(String cid, String cname, String gender, String birthday, String cellphone, String email, String description) {

super();

this.cid = cid;

this.cname = cname;

this.gender = gender;

this.birthday = birthday;

this.cellphone = cellphone;

this.email = email;

this.description = description;

}

public Customer() {

super();

}

}

===============================================================================

com.wyc.cstm.service.CustomerService

import com.wyc.cstm.dao.CustomerDao;

import com.wyc.cstm.domain.Customer;

import com.wyc.cstm.domain.PageBean;

/**

* 業務層 依賴Dao

*/

public class CustomerService {

private CustomerDao customerDao = new CustomerDao();

// /**

// * 查詢所有客戶

// * @return

// */

// public List findAll(){

// return customerDao.findAll();

// }

public PageBean findAll(int pageCode, int pageSize) {

return customerDao.findAll(pageCode, pageSize);

}

/**

* 多條件組合查詢

*

* @param criteria

* @return

*/

public PageBean query(Customer criteria, int pageCode, int pageSize) {

return customerDao.query(criteria, pageCode, pageSize);

}

}

===============================================================================

com.wyc.cstm.web.servlet.CustomerServlet

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.wyc.bean.CommonUtils;

import com.wyc.cstm.domain.Customer;

import com.wyc.cstm.domain.PageBean;

import com.wyc.cstm.service.CustomerService;

import com.wyc.servlet.BaseServlet;

/**

* Web層

*

* @author 31067

*

*/

public class CustomerServlet extends BaseServlet {

private CustomerService customerService = new CustomerService();

// public String findAll(HttpServletRequest request, HttpServletResponse

// response) throws ServletException, IOException {

// /*

// * 1、調用service得到所有客戶

// * 2、將全部信息保存到request域中

// * 3、轉發到list.jsp

// */

// request.setAttribute("cstmList", customerService.findAll());

// return "f:/list.jsp";

// }

public String findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

/*

* 1、獲取頁面傳遞的pageCode

* 2、給定pageSize的值

* 3、使用pageCode和pageSize調用Service方法,得到PageBean對象

* 4、將PageBean對象保存到request域中

* 5、轉發到list.jsp

*/

/*

* 1、得到pageCode有兩種可能

* ? ? 如果pageCode參數不存在,說明pageCode = 1

* ? ? 如果pageCode參數存在,只需要將參數轉換成int類型即可

*/

int pageCode = getPageCode(request);

/*

* 2、給定pageSize的值,每頁10行

*/

int pageSize = 10;

/*

* 3、調用Service的findAll方法

* ? ? 傳遞pageCode和pageSize給Service方法

* ? ? 返回PageBean對象

*/

PageBean pageBean = customerService.findAll(pageCode, pageSize);

/*

* 添加URL及參數

*/

pageBean.setUrl(getUrl(request));

/*

* 4、將PageBean對象保存到request域中

*/

request.setAttribute("pageBean", pageBean);

return "f:list.jsp";

}

private int getPageCode(HttpServletRequest request) {

String value = request.getParameter("pageCode");

if (value == null || value.trim().isEmpty()) {

return 1;

}

return Integer.parseInt(value);

}

// public String query(HttpServletRequest request, HttpServletResponse

// response) throws ServletException, IOException {

// /*

// * 1、封裝表單數據到Customer對象中,它只有四個屬性:cname、gender、cellphone、email

// * 它其實就是一個查詢條件的組合對象

// * 2、調用Service的query()方法,得到List

// * 3、將List保存到request域中

// * 4、轉發到list.jsp

// */

//

// Customer criteria = CommonUtils.toBean(request.getParameterMap(),

// Customer.class);

// List cstmList = customerService.query(criteria);

// request.setAttribute("cstmList", cstmList);

// return "f:list.jsp";

// }

public String query(HttpServletRequest request, HttpServletResponse response) throws Exception {

/*

* 0、把條件參數封裝到Customer對象中 1、獲取頁面傳遞的pageCode 2、給定pageSize的值

* 3、使用pageCode和pageSize以及條件字符串調用Service方法,得到PageBean對象

* 4、將PageBean對象保存到request域中 5、轉發到list.jsp

*/

// 獲取查詢條件

Customer criteria = CommonUtils.toBean(request.getParameterMap(), Customer.class);

/*

* 處理GET請求方式編碼問題

*/

criteria = encoding(criteria);

int pageCode = getPageCode(request);

int pageSize = 10;

PageBean pageBean = customerService.query(criteria, pageCode, pageSize);

/*

* 得到URL,保存到pageBean中

*/

pageBean.setUrl(getUrl(request));

request.setAttribute("pageBean", pageBean);

return "f:list.jsp";

}

/**

* 處理數據的編碼問題

*

* @throws Exception

*/

private Customer encoding(Customer criteria) throws Exception {

String cname = criteria.getCname();

String gender = criteria.getGender();

String cellphone = criteria.getCellphone();

String email = criteria.getEmail();

if (cname != null && !cname.trim().isEmpty()) {

cname = new String(cname.getBytes("iso-8859-1"), "utf-8");

criteria.setCname(cname);

}

if (gender != null && !gender.trim().isEmpty()) {

gender = new String(gender.getBytes("iso-8859-1"), "utf-8");

criteria.setGender(gender);

}

if (cellphone != null && !cellphone.trim().isEmpty()) {

cellphone = new String(cellphone.getBytes("iso-8859-1"), "utf-8");

criteria.setCellphone(cellphone);

}

if (email != null && !email.trim().isEmpty()) {

email = new String(email.getBytes("iso-8859-1"), "utf-8");

criteria.setEmail(email);

}

return criteria;

}

/**

* 截取請求URL /項目名/Servlet路徑?參數字符串

*

* @param request

* @return

*/

private String getUrl(HttpServletRequest request) {

// 獲取項目名

String contextPath = request.getContextPath();

// 獲取ServletPath,即/CustomerServlet

String servletPath = request.getServletPath();

// 獲取問號之后的參數部分

String queryString = request.getQueryString();

/*

* 判斷queryString中是否包含pageCode 如果包含,需要截取掉pageCode

*/

if (queryString.contains("&pageCode=")) {

int index = queryString.lastIndexOf("&pageCode=");

queryString = queryString.substring(0, index);

}

return contextPath + servletPath + "?" + queryString;

}

}

===============================================================================

c3p0-config.xml

jdbc:mysql://localhost:3306/customers

com.mysql.jdbc.Driver

root

Admin123

3

10

2

10

===============================================================================

frame.jsp

String path = request.getContextPath();

String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

%>

主頁

===============================================================================

list.jsp

String path = request.getContextPath();

String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

%>

My JSP 'list.jsp' starting page姓名性別生日手機號碼郵箱描述

要遍歷的是pageBean對象的beanList集合

--%>

${cstm.cname }${cstm.gender }${cstm.birthday }${cstm.cellphone }${cstm.email }${cstm.description }

編輯

刪除

給出分頁相關的鏈接

--%>

進行設置了 --%>

首頁

上一頁

= 10 --%>

[${i }]

${i }

下一頁

尾頁

第${pageBean.pageCode }頁/共${pageBean.totalPages }頁

===============================================================================

query.jsp

String path = request.getContextPath();

String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

%>

My JSP 'query.jsp' starting page

高級搜索

客戶名稱
客戶性別

請選擇

手機
郵箱
?

===============================================================================

top.jsp

String path = request.getContextPath();

String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";

%>

My JSP 'top.jsp' starting page

客戶關系管理系統

添加客戶 ?|

查詢客戶 |

高級搜索 |

返回首頁

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的java 分页查询_JavaWeb之分页查询的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。