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<T> {
    // 當前頁碼pageCode
    private int pageCode;
 
    /*
     * 總頁數
     * 通過計算得出,不允許外界設置值
     * 因為只能get,所以不需要成員變量,通過計算即可得出
     */
    // private int totalPages;
 
    // 總記錄數
    private int totalRecord;
 
    // 每頁記錄數
    private int pageSize;
 
    // 當前頁的記錄
    private List<T> 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<T> getBeanList() {
        return beanList;
    }
 
    public void setBeanList(List<T> 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<T> 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<T>,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<Customer> findAll() {
    // try {
    // String sql = "select * from customer";
    // return qr.query(sql, new BeanListHandler<Customer>(Customer.class));
    // } catch (Exception e) {
    // throw new RuntimeException(e);
    // }
    // }
 
    public PageBean<Customer> findAll(int pageCode, int pageSize) {
        try {
            /*
             * 1、創建PageBean對象 2、設置PageBean對象的pageCode和pageSize
             * 3、得到totalRecord,設置給pageBean 4、得到beanList,設置給pageBean 5、返回pageBean
             */
            PageBean<Customer> pageBean = new PageBean<Customer>();
            /*
             * 設置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<Customer> beanList = qr.query(sql, new BeanListHandler<Customer>(Customer.class), params);

            pageBean.setBeanList(beanList);
 
            return pageBean;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 多條件組合查詢
     * 
     * @param criteria
     * @return
     */
    // public List<Customer> 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<Object> params = new ArrayList<Object>();
    //
    //
    // 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>(Customer.class), params.toArray());
    // } catch (SQLException e) {
    // throw new RuntimeException(e);
    // }
    // }
 
    public PageBean<Customer> query(Customer criteria, int pageCode, int pageSize) {
        try {
            /*
             * 1、創建PageBean對象 2、設置已有屬性,pageCode和pageSize 3、得到totalRecord
             * 4、得到BeanList
             */
            /*
             * 創建PageBean對象,設置已有屬性
             */
            PageBean<Customer> pageBean = new PageBean<Customer>();
            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<Object> params = new ArrayList<Object>();
 
            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<Customer> beanList = qr.query(sql.append(whereSql).append(limitSql).toString(), new BeanListHandler<Customer>(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<Customer> findAll(){
    // return customerDao.findAll();
    // }
 
    public PageBean<Customer> findAll(int pageCode, int pageSize) {
        return customerDao.findAll(pageCode, pageSize);
    }
 
    /**
     * 多條件組合查詢
     * 
     * @param criteria
     * @return
     */
    public PageBean<Customer> 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<Customer> 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<Customer>
    // * 3、將List<Customer>保存到request域中
    // * 4、轉發到list.jsp
    // */
    //
    // Customer criteria = CommonUtils.toBean(request.getParameterMap(),
    // Customer.class);
    // List<Customer> 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<Customer> 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

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- 默認配置 -->
    <default-config>
        <!-- 連接四大參數配置 -->
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/customers</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">Admin123</property>
        <!-- 連接池參數配置 -->
        <property name="acquireIncrement">3</property>
        <property name="initialPoolSize">10</property>
        <prpperty name="minPoolSize">2</prpperty>
        <property name="maxPoolSize">10</property>
    </default-config>
</c3p0-config>
 
 
 




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

frame.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri=" http://java.sun.com/jsp/jstl/core" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
 
<title>主頁</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
 
</head>
    <frameset rows="20%, *" >
        <frame src="<c:url value='/top.jsp'/>" name="top">
        <frame src="<c:url value='/welcome.jsp'/>" name="main">
    </frameset>
</html>
 




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

list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri=" http://java.sun.com/jsp/jstl/core"%>
 
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
 
<title>My JSP 'list.jsp' starting page</title>
 
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
 
</head>
 
<body>
    <table align="center" border="1px">
        <tr>
            <th>姓名</th>
            <th>性別</th>
            <th>生日</th>
            <th>手機號碼</th>
            <th>郵箱</th>
            <th>描述</th>
        </tr>
        <%--
            要遍歷的是pageBean對象的beanList集合
        --%>
        <c:forEach items="${requestScope.pageBean.beanList }" var="cstm">
            <tr>
                <td>${cstm.cname }</td>
                <td>${cstm.gender }</td>
                <td>${cstm.birthday }</td>
                <td>${cstm.cellphone }</td>
                <td>${cstm.email }</td>
                <td>${cstm.description }</td>
                <td>
                    <a href="<c:url value='/CustomerServlet?method=preEdit&cid=${cstm.cid }'/>">編輯</a>
                    <a href="<c:url value='/CustomerServlet?method=delete&cid=${cstm.cid }'/>">刪除</a>
                </td>
            </tr>
        </c:forEach>
 
    </table>
    <%--
        給出分頁相關的鏈接
 --%>
 <center>
        <%-- 因為pageBean中保存了當前頁的URL,並且包括項目名和Servlet路徑與參數,所以可以不用<c:url />進行設置了 --%>
        <%-- 因為pageBean中的URL不包含pageCode,所以依然需要手動添加 --%>
        <a href="${pageBean.url }&pageCode=1" >首頁</a>
        <c:if test="${pageBean.pageCode > 1 }">
            <a href="${pageBean.url }&pageCode=${pageBean.pageCode-1 }" >上一頁</a>
        </c:if>
 
        <%-- 分頁頁碼列表 --%>
 
        <%-- 計算begin和end --%>
        <c:choose>
            <%-- 當總頁數小於10,那么就把所有的頁數都顯示出來 --%>
            <c:when test="${pageBean.totalPages <= 10 }">
                <c:set var="begin" value="1" />
                <c:set var="end" value="${pageBean.totalPages }" />
            </c:when>
 
            <%-- 當總頁數 >= 10 --%>
            <c:when test="${pageBean.totalPages > 10 }">
                <c:set var="begin" value="${pageBean.pageCode - 5 }" />
                <c:set var="end" value="${pageBean.totalPages + 4 }" />
 
                <%-- begin溢出 --%>
                <c:if test="${begin < 1 }">
                    <c:set var="begin" value="1" />
                    <%-- 因為begin已經溢出,所以表示總頁數不足10頁 --%>
                    <c:set var="end" value="${pageBean.totalPages }" />
                </c:if>
 
                <%-- end溢出 --%>
                <c:if test="${end > pageBean.totalPages }">
                    <%-- 因為end溢出,所以begin = end - 9 --%>
                    <c:set var="begin" value="${pageBean.totalPages - 9 }" />
                    <c:set var="end" value="${pageBean.totalPages }" />
                </c:if>
            </c:when>
        </c:choose>
 
        <%-- 循環顯示頁碼列表 --%>
        <c:forEach var="i" begin="${begin }" end="${end }">
        <c:choose>
            <%-- 當前頁碼與頁碼列表相同時,輸出簡單文本 --%>
            <c:when test="${pageBean.pageCode eq i }">
                [${i }]
           </c:when>
            <c:otherwise>
                <a href="${pageBean.url }&pageCode=${i }">${i }</a>
            </c:otherwise>
        </c:choose>
    </c:forEach>
 
 
    <c:if test="${pageBean.pageCode < pageBean.totalPages }">
        <a href="${pageBean.url }&pageCode=${pageBean.pageCode+1 }" >下一頁</a>
    </c:if>
 
    <a href="${pageBean.url }&pageCode=${pageBean.totalPages }" >尾頁</a>
    第${pageBean.pageCode }頁/共${pageBean.totalPages }頁
 
    </center>
</body>
</html>
 




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

query.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri=" http://java.sun.com/jsp/jstl/core"%>
 
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
 
<title>My JSP 'query.jsp' starting page</title>
 
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
 
</head>
 
<body>
    <h3 align="center">高級搜索</h3>
    <form action="<c:url value='/CustomerServlet' />" method="get">
        <input type="hidden" name="method" value="query" />
        <table border="0" align="center" width="40%" style="margin-left: 100px;">
            <tr>
                <td width="100px">客戶名稱</td>
                <td>
                    <input type="text" name="cname" />
                </td>
            </tr>
            <tr>
                <td>客戶性別</td>
                <td>
                    <select name="gender">
                        <option value="">請選擇</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td>手機</td>
                <td>
                    <input type="text" name="cellphone" />
                </td>
            </tr>
            <tr>
                <td>郵箱</td>
                <td>
                    <input type="text" name="email" />
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="搜索"/>
                    <input type="reset" value="重置" />
                </td>
             </tr>
        </table>
    </form>
</body>
</html>
 




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

top.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri=" http://java.sun.com/jsp/jstl/core"%>
 
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
 
<!-- 它的作用是為本頁面中所有的表單和超鏈接指定顯示內容的框架 -->
<!-- 在base中寫targe,相當於在本頁面中的所有a標簽中添加target -->
<base target="main">
 
<title>My JSP 'top.jsp' starting page</title>
 
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
 
</head>
 
<body style="text-align: center">
    <h1>客戶關系管理系統</h1>
    <a href="<c:url value='/add.jsp'/>">添加客戶</a>  |
    <a href="<c:url value='/CustomerServlet?method=findAll' />">查詢客戶</a> |
    <a href="<c:url value='/query.jsp'/>">高級搜索</a> |
    <a href="<c:url value='/welcome.jsp' />">返回首頁</a>
</body>
</html>


免責聲明!

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



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