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>
posted @ 2017-02-07 17:58  WWWYC  阅读(4012)  评论(1编辑  收藏  举报