zoukankan      html  css  js  c++  java
  • JSP分页1

    分页

    1、什么分页?

    第N页/共M页 首页 上一页 1 2 3 4 5 6 7 8 9 10 下一页 尾页 口 go

    分页的优点:只查询一页,不用查询所有页!

    2、分页数据
    页面的数据都是由Servlet传递来的!
    Servlet:
    当前页:PageCode,pc;
    pc:如果页面没有传递当前页码,那么Servlet默认是第一页,或者按页面传递的为准!
    总页数:totalPage,tp
    tp:总记录数/每页记录数
    总记录数:totalRecord,tr
    tr:dao来获取,select count(*) from t_customer
    每页记录数:业务数据或者叫系统数据。10条
    当前页数据:beanList
    url

    3、数据的传递
    这些分页数据总要在各层之间来回的传递!
    我们把这些分页数据封装到一个javaBean中,它就叫分页Bean,例如:PageBean

    4、分页在各层中的处理
    页面:给出分页相关的链接们!
    页面需要给servlet传递什么?当前页码
    servlet:创建PageBean对象,给pageBean的所有的属性赋值然后传递给页面
    Servlet需要给dao传递pc,ps
    service:略
    dao:
    tr:select count(*) from t_customer
    beanList: select * from t_customer limit x,y

    mysql 分页语句: 

    sql="SELECT * FROM t_customer ORDER BY cname LIMIT ?,?";

    oracle分页语句:

    sql="select * from (select rownum r,t.* from (select * from profile order by id) t) tb where r>? and r<=?";

    oracle中要注意rownum是一个伪列,最好使用别名,有些地方比如>=或者in直接使用rownum就是无效的。

    例子:

    oracle做的:

    package com.domain;
    
    import java.util.List;
    
    public class PageBean <T>{
        private int pc;//page code 当前页码
        private int tp;//total page 总页数
        private int tr;//totalRecoed 总记录数
        private int ps;//page size 每页的记录数
        private List<T> beanList;//当前页转载的bean集合
        public PageBean() {
            super();
        }
        public PageBean(int pc, int tp, int tr, int ps, List<T> beanList) {
            super();
            this.pc = pc;
            this.tp = tp;
            this.tr = tr;
            this.ps = ps;
            this.beanList = beanList;
        }
        @Override
        public String toString() {
            return "PageBean [pc=" + pc + ", tp=" + tp + ", tr=" + tr + ", ps="
                    + ps + ", beanList=" + beanList + "]";
        }
        public int getPc() {
            return pc;
        }
        public void setPc(int pc) {
            this.pc = pc;
        }
        public int getTp() {
            tp=tr/ps;
            return tr%ps==0?tp:tp+1;
        }
        public void setTp(int tp) {
            this.tp = tp;
        }
        public int getTr() {
            return tr;
        }
        public void setTr(int tr) {
            this.tr = tr;
        }
        public int getPs() {
            return ps;
        }
        public void setPs(int ps) {
            this.ps = ps;
        }
        public List<T> getBeanList() {
            return beanList;
        }
        public void setBeanList(List<T> beanList) {
            this.beanList = beanList;
        }
        
        
    }
    
    dao中的findAll:
    public PageBean<Profile> findAll(int pc,int ps){
            PageBean<Profile> pb=new PageBean<Profile>();
            pb.setPc(pc);
            pb.setPs(ps);
            
            QueryRunner qr=new QueryRunner();
            Connection con;
            try {
                con = JdbcUtils.getConnection();
                String sql="SELECT COUNT(*) FROM profile";
                Number tr1=(Number) qr.query(con,sql, new ScalarHandler());
                int tr=tr1.intValue();
                pb.setTr(tr);
                int tp=tr%ps==0?tr/ps:tr/ps+1;
                pb.setTp(tp);
                //System.out.println(tp+"  "+pc+"  "+ps+"  "+ps*(pc-1)+"  "+ps*pc);
                //sql="SELECT * FROM profile order by id where rownum>? and rownum<=?";
                sql="select * from (select rownum r,t.* from (select * from profile order by id) t) tb where r>? and r<=?";
                Object[] params={ps*(pc-1),ps*pc};
                ResultSetHandler<List<Profile>> rsh=new BeanListHandler<Profile>(Profile.class);
                List<Profile> beanList=(ArrayList<Profile>) qr.query(con, sql, rsh,params);
                pb.setBeanList(beanList);
                JdbcUtils.releaseConnection(con);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            return pb;
        }
    
    service中的findAll:
    public PageBean<Profile> findAll(int pc,int ps){
                return profileDao.findAll(pc,ps);
        }
    
    
    直接使用的jsp:
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ page import="com.domain.Profile,java.sql.Date,com.service.ProfileService,java.text.SimpleDateFormat,com.domain.PageBean" %>
    
    <%
    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">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
        <style type="text/css">
            td{
            /* 80px; */
             border:1px solid;
            }
            table{
             border:1px solid;
            }
            #tr1{
            background-color: yellow;
            }
        </style>
        <script type="text/javascript" src="js/jquery1.8.3.js"></script>
        <script type="text/javascript" src="js/list.js"></script>
      </head>
      <% 
              ProfileService profileService=new ProfileService();
              String pco=request.getParameter("pc");
              int pc;
              if(pco==null) pc=1;
              else pc=Integer.parseInt(request.getParameter("pc"));
              int ps=10;
              PageBean<Profile> pb=profileService.findAll(pc,ps);
              request.setAttribute("pb",pb);
              //System.out.println(pb);
              List<Profile> profiles=pb.getBeanList();
      %>
          <%!
              
              String date2Str(Date d){
                  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                  return sdf.format(d);
              }
          %>
      <body>
        <table>
            <tr id="tr1">
                <td>编号</td>
                <td>姓名</td>
                <td>生日</td>
                <td>性别</td>
                <td>职业</td>
                <td>住所</td>
                <td>电话</td>
                <td>操作</td>
            </tr>
            <%for(Profile p:profiles){%>
            <tr>
                <td><%=p.getId() %></td>
                <td><%=p.getName() %></td>
                <td><%=date2Str(p.getBirthday()) %></td>
                <td><%=p.getGender() %></td>
                <td><%=p.getCareer() %></td>
                <td><%=p.getAddress() %></td>
                <td><%=p.getMobile() %></td>
                <td>
                    <button name="show" >明细</button>
                    <button  name="alert" >修改</button>
                    <button name="delete" >删除</button>
                </td>
            </tr>
            <%
            }
            %>
            
        </table>
        <br/>
        
        <c:choose>
            <c:when test="${pb.pc!=1 }">
                 <a href="<c:url value='/list.jsp?pc=1'/>">首页</a>
                 <a href="<c:url value='/list.jsp?pc=${pb.pc-1 }'/>">上一页</a>
            </c:when>
            <c:otherwise>
                首页
                上一页
            </c:otherwise>
        </c:choose>
           <c:choose>
            <c:when test="${pb.pc!=pb.tp }">
                <a href="<c:url value='/list.jsp?pc=${pb.pc+1 }'/>">下一页</a>
                <a href="<c:url value='/list.jsp?pc=${pb.tp }'/>">尾页</a>
            </c:when>
            <c:otherwise>
                下一页
                尾页
            </c:otherwise>
        </c:choose>
      
      </body>
    </html>
    View Code

    mysql做的:

    public PageBean findAll(int pc,int ps){
            try{
                /*
                 *  1、创建PageBean对象pb
                 *  2、设置pb的pc和ps
                 *  3、得到tr,设置给pb
                 *  4、得打beanList,设置给pb
                 *  5、返回pb
                 */
                
                PageBean<Customer> pb=new PageBean<Customer>();
                pb.setPc(pc);
                pb.setPs(ps);
                /*
                 * 得到tr
                 */
                String sql="SELECT COUNT(*) FROM t_customer";
                Number num=(Number)qr.query(sql, new ScalarHandler());
                int tr=num.intValue();
                pb.setTr(tr);
                /*
                 * 得到beanList
                 */
                sql="SELECT * FROM t_customer ORDER BY cname LIMIT ?,?";
                Object[] params={(pc-1)*ps,ps};
                List<Customer> beanList=qr.query(sql, new BeanListHandler<Customer>(Customer.class),params);
                pb.setBeanList(beanList);
                return pb;
            }catch(SQLException e){
                throw new RuntimeException(e);
            }
        }
    
    package cn.itcast.cus.domain;
    
    import java.util.List;
    
    public class PageBean<T> {
        private int pc;//当前页码 Page code
        private int tp;//总页数 total page
        private int tr;//总记录数 total record
        private int ps;//每页记录数pahe size
        private List<T> beanList;//当前页的记录
        public int getPc() {
            return pc;
        }
        public void setPc(int pc) {
            this.pc = pc;
        }
        public int getTp() {
            //通过总记录数和每页记录数的到总页数
            tp= tr/ps;
            return tr%ps==0?tp:tp+1;
        }
        public void setTp(int tp) {
            this.tp = tp;
        }
        public int getTr() {
            return tr;
        }
        public void setTr(int tr) {
            this.tr = tr;
        }
        public int getPs() {
            return ps;
        }
        public void setPs(int ps) {
            this.ps = ps;
        }
        public List<T> getBeanList() {
            return beanList;
        }
        public void setBeanList(List<T> beanList) {
            this.beanList = beanList;
        }
        public PageBean() {
            super();
        }
        public PageBean(int pc, int tp, int tr, int ps, List<T> beanList) {
            super();
            this.pc = pc;
            this.tp = tp;
            this.tr = tr;
            this.ps = ps;
            this.beanList = beanList;
        }
        
        
    
    }
    
    package cn.itcast.cus.service;
    
    import java.util.List;
    
    import cn.itcast.cus.dao.CustomerDao;
    import cn.itcast.cus.domain.Customer;
    import cn.itcast.cus.domain.PageBean;
    
    public class CustomerService {
        private CustomerDao customerDao=new CustomerDao();
        
        public void addCustomer(Customer customer){
            customerDao.add(customer);
        }
        
    //    public List<Customer> findAll(){
    //        return customerDao.findAll();
    //    }
        public PageBean findAll(int pc,int ps){
            return customerDao.findAll(pc,ps);
        }
        
        public Customer load(String cid){
            return customerDao.load(cid);
        }
        
        public void update(Customer c){
            customerDao.update(c);
        }
    
        public void delete(String cid) {
            customerDao.delete(cid);
        }
    
        public List<Customer> query(Customer c) {
            return customerDao.query(c);
        }
        
    }
    
    public String findAll(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            /* 1、获取页面传递的pc
             * 2、给定ps的值
             * 3、使用pc和ps调用service方法,得到PageBean保存到request域
             * 4、转发到list.jsp
             */
            /*
             * 1、得到pc
             *  如果pc参数不存在,pc为1
             *  如果pc参数存在,需要转换为int类型即可
             */
            int pc=getPc(request);//得到pc
            int ps=10;//给定ps的值
            PageBean<Customer> pb=customerService.findAll(pc,ps);//传递pc,ps给Service,得到PageBean
            request.setAttribute("pb", pb);//保存到request域中
            return "f:/list.jsp";//转发到list.jsp
            
        }
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <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">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
    <h3 align="center">客户列表</h3>
    <table border="1" width="70%" align="center">
        <tr>
            <th>客户姓名</th>
            <th>性别</th>
            <th>生日</th>
            <th>手机</th>
            <th>邮箱</th>
            <th>描述</th>
            <th>操作</th>
        </tr>
        <!-- 要遍历的是PageBean的beanList这个集合 -->
        <c:forEach var="c" items="${pb.beanList }">
        <tr>
            <td>${c.cname }</td>
            <td>${c.gender }</td>
            <td>${c.birthday }</td>
            <td>${c.cellphone }</td>
            <td>${c.email }</td>
            <td>${c.description }</td>
            <td>
                <a href="<c:url value='/CustomerServlet?cid=${c.cid }&method=preEdit'/>">编辑</a>
                <a href="<c:url value='/CustomerServlet?cid=${c.cid }&method=delete'/>">删除</a>
            </td>
        </tr>
        </c:forEach>
    </table>
    <br/>
    <%--
    给出分页相差的链接
     --%>
     <center>
     第${pb.pc }页/共${pb.tp }页
     <a href="<c:url value='/CustomerServlet?method=findAll&pc=1'/> ">首页</a>
     <c:if test="${pb.pc>1 }">
     <a href="<c:url value='/CustomerServlet?method=findAll&pc=${pb.pc-1 }'/> ">上一页</a>
     </c:if>
     <c:if test="${pb.pc<pb.tp }">
     <a href="<c:url value='/CustomerServlet?method=findAll&pc=${pb.pc+1 }'/>">下一页</a>
     </c:if>
     <a href="<c:url value='/CustomerServlet?method=findAll&pc=${pb.tp }'/>">尾页</a>
     </center>
      </body>
    </html>
    View Code

    5、显示分页页码列表
    1 2 3 4 5 6 7 8 9 10
    最多显示多少个页码!定位10;
    当前页,在页码列表中的位置,定位6;
    只需要当前页来定出来页码列表!
    定下来页码列表只需要两样数据:
    begin
    end
    10 11 12 13 14 (15) 16 17 18 19
    需要使用pc来退算出begin和end
    begin=pc-5
    end=pc+4
    计算公式:
    如果总页数<=10(列表长度,那么begin=1,end=总页数)
    使用公式计算:begin=pc-5,end=pc+4;
    头溢出:当begin<1时让begin=1
    尾溢出:当end>${tp},让end=${tp}

    注意:尾溢出应该先于头溢出判断

    6、在超链接中要保留参数
    当使用多条件查询之后,然后在点击第2页时,这个第二页的超链接没有条件了,所以会丢失条件,所以我们需要在页面上的所有链接都要保留条件!
    我们要把条件以一个字符串的形式保存到PageBean的url中!这个任务交给Servlet!
    post中的数据无法从url获取 表单会自动将中文参数转成url编码

    这两点事如果存在高级查询的时候分页改进的。

    例子:

    加入字段url,保存之前查询的url,剔除页码

    package cn.itcast.cus.domain;
    
    import java.util.List;
    
    public class PageBean<T> {
        private int pc;//当前页码 Page code
        private int tp;//总页数 total page
        private int tr;//总记录数 total record
        private int ps;//每页记录数pahe size
        private List<T> beanList;//当前页的记录
        
        private String url;//这个就是url后的条件!
        
        public int getPc() {
            return pc;
        }
        public void setPc(int pc) {
            this.pc = pc;
        }
        public int getTp() {
            //通过总记录数和每页记录数的到总页数
            tp= tr/ps;
            return tr%ps==0?tp:tp+1;
        }
        public void setTp(int tp) {
            this.tp = tp;
        }
        public int getTr() {
            return tr;
        }
        public void setTr(int tr) {
            this.tr = tr;
        }
        public int getPs() {
            return ps;
        }
        public void setPs(int ps) {
            this.ps = ps;
        }
        public List<T> getBeanList() {
            return beanList;
        }
        public void setBeanList(List<T> beanList) {
            this.beanList = beanList;
        }
        public PageBean() {
            super();
        }
        public PageBean(int pc, int tp, int tr, int ps, List<T> beanList,String url) {
            super();
            this.pc = pc;
            this.tp = tp;
            this.tr = tr;
            this.ps = ps;
            this.beanList = beanList;
            this.url=url;
        }
        public String getUrl() {
            return url;
        }
        public void setUrl(String url) {
            this.url = url;
        }
        
        
    
    }
    PageBean

    list.jsp中域页码有关的设置

    <br/>
    <%--
    给出分页相差的链接
     --%>
     <center>
     第${pb.pc }页/共${pb.tp }页
     
     <a href="${pb.url }&pc=1">首页</a>
     <c:if test="${pb.pc>1 }">
     <a href="${pb.url }&pc=${pb.pc-1 }">上一页</a>
     </c:if>
     
     <!-- 计算begin和end者两个东西 -->
     <c:choose>
         <%-- 如果总页数不足10页,那么把所有的页数都显示出来  --%>
         <c:when test="${bp.tp<=10 }">
             <c:set var="begin" value="1"/>
             <c:set var="end" value="${pb.tp}"/>
         </c:when>
         <%-- 当总页数>10时,通过公式计算begin和end --%>
         <c:otherwise>
             <c:set var="begin" value="${pb.pc-5 }"/>
             <c:set var="end" value="${pb.pc+4 }"/>
             <%-- 尾溢出 --%>
             <c:if test="${end>pb.tp }">
                 <c:set var="begin" value="${pb.tp-9 }"/>
                 <c:set var="end" value="${pb.tp }"/>
             </c:if>
             <%-- 注意尾溢出要在头溢出之前 --%>
             <%-- 头溢出 --%>
             <c:if test="${begin<1 }">
                 <c:set var="begin" value="1" />
                 <c:set var="end" value="10" />
             </c:if>
         </c:otherwise>
     </c:choose>
     <%-- 循环遍历页码列表 --%>
     <c:forEach var="i" begin="${begin }" end="${end }">
         <c:choose>
             <c:when test="${i eq pb.pc }">
                 [${i }]
             </c:when>
             <c:otherwise>
                 <a href="${pb.url }&pc=${i}">[${i }]</a>
             </c:otherwise>
         </c:choose>
         
     </c:forEach>
     
     <c:if test="${pb.pc<pb.tp }">
     <a href="${pb.url }&pc=${pb.pc+1 }">下一页</a>
     </c:if>
     <a href="${pb.url }&pc=${pb.tp }">尾页</a>
     </center>
    list.jsp

    query.jsp中的提交方式一定要改成get,因为post方式无法从url中获取参数 request.getQueryString()

    <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 width="40%">
                <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>
            <td>
                <label id="cellphoneError" class="error">&nbsp;</label>
            </td>        
        </tr>
        <tr>
            <td>邮箱</td>
            <td>
                <input type="text" name="email"/>
            </td>
            <td>
                <label id="emailError" class="error">&nbsp;</label>
            </td>    
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>
                <input type="submit" value="搜索"/>
                <input type="reset" value="重置"/>
            </td>
            <td>&nbsp;</td>
        </tr>
    </table>
    </form>
    View Code

    customerDao中查询方法中关于sql语句的拼接可以参考下

    public PageBean findAll(int pc,int ps){
            try{
                /*
                 *  1、创建PageBean对象pb
                 *  2、设置pb的pc和ps
                 *  3、得到tr,设置给pb
                 *  4、得打beanList,设置给pb
                 *  5、返回pb
                 */
                
                PageBean<Customer> pb=new PageBean<Customer>();
                pb.setPc(pc);
                pb.setPs(ps);
                /*
                 * 得到tr
                 */
                String sql="SELECT COUNT(*) FROM t_customer";
                Number num=(Number)qr.query(sql, new ScalarHandler());
                int tr=num.intValue();
                pb.setTr(tr);
                /*
                 * 得到beanList
                 */
                sql="SELECT * FROM t_customer ORDER BY cname LIMIT ?,?";
                Object[] params={(pc-1)*ps,ps};
                List<Customer> beanList=qr.query(sql, new BeanListHandler<Customer>(Customer.class),params);
                pb.setBeanList(beanList);
                return pb;
            }catch(SQLException e){
                throw new RuntimeException(e);
            }
        }
    
    public PageBean<Customer> query(Customer c,int pc,int ps) {
            
            try {
                /*
                 * 1、创建PageBean对象
                 * 2、设置已有属性,pc和ps
                 * 3、得到tr
                 * 4、得到beanList
                 */
                PageBean pb=new PageBean();
                pb.setPc(pc);
                pb.setPs(ps);
                /*
                 * 得到tr
                 */
                StringBuilder cntSql=new StringBuilder("SELECT COUNT(*) FROM t_customer");
                StringBuilder whereSql=new StringBuilder(" WHERE 1=1");
                ArrayList<Object> params=new ArrayList<Object>();
                
                String cname=c.getCname();
                if(cname!=null&& !cname.trim().isEmpty()){
                    whereSql.append(" and cname like ?");
                    params.add("%"+cname+"%");
                }
                String gender=c.getGender();
                if(gender!=null&&!gender.trim().isEmpty()){
                    whereSql.append(" and gender=?");
                    params.add(gender);
                }
                String cellphone=c.getCellphone();
                if(cellphone!=null &&!cellphone.trim().isEmpty()){
                    whereSql.append(" and cellphone like ?");
                    params.add("%"+cellphone+"%");
                }
                String email=c.getEmail();
                if(email!=null && !email.trim().isEmpty()){
                    whereSql .append(" and email like ?");
                    params.add("%"+email+"%");
                }
                
                /*
                 * select count(*)...+where ...
                 * 执行之
                 */
                Number num=(Number)qr.query(cntSql.append(whereSql).toString(), new ScalarHandler(),params.toArray());
    //            System.out.println(1+" :"+cntSql.append(whereSql).toString());
                int tr=num.intValue();
                pb.setTr(tr);
                /*
                 * 得到beanList
                 */
                StringBuilder sql=new StringBuilder("SELECT * FROM t_customer");
                //我们查询beanList这一步还需要给出limit字据
                StringBuilder limitSql=new StringBuilder(" limit ?,?");
                //params中需要给limit后两个问号对应的值
                params.add((pc-1)*ps);
                params.add(ps);
                //执行之
                List<Customer> beanList=(List<Customer>) qr.query(sql.append(whereSql).append(limitSql).toString(),new BeanListHandler<Customer>(Customer.class),params.toArray());
    //            System.out.println(2+" : "+sql.append(whereSql).append(limitSql).toString());
                pb.setBeanList(beanList);
                
    //            System.out.println(pb.getPc()+" "+pb.getTp());
                return pb;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    customerDao
    package cn.itcast.cus.service;
    
    import java.util.List;
    
    import cn.itcast.cus.dao.CustomerDao;
    import cn.itcast.cus.domain.Customer;
    import cn.itcast.cus.domain.PageBean;
    
    public class CustomerService {
        private CustomerDao customerDao=new CustomerDao();
        
        public void addCustomer(Customer customer){
            customerDao.add(customer);
        }
        
    //    public List<Customer> findAll(){
    //        return customerDao.findAll();
    //    }
        public PageBean findAll(int pc,int ps){
            return customerDao.findAll(pc,ps);
        }
        
        public Customer load(String cid){
            return customerDao.load(cid);
        }
        
        public void update(Customer c){
            customerDao.update(c);
        }
    
        public void delete(String cid) {
            customerDao.delete(cid);
        }
    
    //    public List<Customer> query(Customer c) {
    //        return customerDao.query(c);
    //    }
        public PageBean<Customer> query(Customer c,int pc,int ps) {
            return customerDao.query(c,pc,ps);
        }
        
    }
    service

    customerServlet:这个比较重要

    package cn.itcast.cus.web.servlet;
    
    
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import cn.itcast.cus.domain.Customer;
    import cn.itcast.cus.domain.PageBean;
    import cn.itcast.cus.service.CustomerService;
    import cn.itcast.servlet.BaseServlet;
    import cn.itcast.utils.CommonUtils;
    
    public class CustomerServlet extends BaseServlet {
        private static final long serialVersionUID = 1L;
        CustomerService customerService=new CustomerService();
        
        public String add(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            /*
             * 1、补全表单数据到Customer对象
             * 2、补全Cid,使用uuid
             * 3、使用service方法完成添加工作
             * 4.向request域中保存成功信息
             * 5、转发到msg.jsp
             */
            Customer c=CommonUtils.toBean(request.getParameterMap(), Customer.class);
            c.setCid(CommonUtils.uuid());
            customerService.addCustomer(c);
            request.setAttribute("msg", "恭喜!注册成功");
            return "f:/msg.jsp";
        }
        
    //    public String findAll(HttpServletRequest request, HttpServletResponse response)
    //            throws ServletException, IOException {
    //        /*
    //         * 1、直接调用service方法,得到查询结果
    //         * 2、查询结果保存到request域中
    //         * 3、转发到list.jsp
    //         */
    //        List<Customer> customers= customerService.findAll();
    //        request.setAttribute("customers", customers); 
    //        return "f:/list.jsp";
    //    }
        
        public String findAll(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            /* 1、获取页面传递的pc
             * 2、给定ps的值
             * 3、使用pc和ps调用service方法,得到PageBean保存到request域
             * 4、转发到list.jsp
             */
            /*
             * 1、得到pc
             *  如果pc参数不存在,pc为1
             *  如果pc参数存在,需要转换为int类型即可
             */
            int pc=getPc(request);//得到pc
            int ps=10;//给定ps的值
            PageBean<Customer> pb=customerService.findAll(pc,ps);//传递pc,ps给Service,得到PageBean
            pb.setUrl(getUrl(request));
            request.setAttribute("pb", pb);//保存到request域中
            return "f:/list.jsp";//转发到list.jsp
            
        }
        /**
         * 得到pc的方法
         * @param request
         * @return
         */
        private int getPc(HttpServletRequest request){
            String pc=request.getParameter("pc");
            if(pc==null) return 1;
            return Integer.parseInt(pc);
        }
        
        public String preEdit(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            /*
             * 1、直接调用service方法,得到查询结果
             * 2、查询结果保存到request域中
             * 3、转发到EDIT.jsp
             */
            String cid=request.getParameter("cid");
            Customer c=customerService.load(cid);
            request.setAttribute("customer", c); 
            return "f:/edit.jsp";
        }
        
        public String edit(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            /*
             * 1、封装表单数据到Customer对象中
             * 2、调用service完成编辑
             * 3、保存成功信息到request域
             * 4、转发到msg.jsp显示成功信息
             */
            Customer c=CommonUtils.toBean(request.getParameterMap(), Customer.class);
            customerService.update(c);
            request.setAttribute("msg", "恭喜,修改成功!"); 
            return "f:/msg.jsp";
        }
        
        public String delete(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            /*
             * 1、封装表单数据到Customer对象中
             * 2、调用service完成编辑
             * 3、保存成功信息到request域
             * 4、转发到msg.jsp显示成功信息
             */
            String cid=request.getParameter("cid");
            customerService.delete(cid);
            request.setAttribute("msg", "恭喜,删除成功!"); 
            return "f:/msg.jsp";
        }
        
    //    public String query(HttpServletRequest request, HttpServletResponse response)
    //            throws ServletException, IOException {
    //        /*
    //         * 1、封装表单数据到Customer对象中
    //         * 2、调用service完成编辑
    //         * 3、保存查询到request域
    //         * 4、转发到list.jsp
    //         */
    //        Customer criteria=CommonUtils.toBean(request.getParameterMap(), Customer.class);
    //        List<Customer> customers=customerService.query(criteria);
    //        request.setAttribute("customers", customers); 
    //        return "f:/list.jsp";
    //    }
        
        public String query(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            //System.out.println(getUrl(request));
            /*
             * 0、把条件封装到customer对象中
             * 1、得到pc
             * 2、给定ps
             * 3、使用pc和ps以及条件对象得到pageBean
             * 4、把pageBean保存到request域中
             * 5、转发到list.jsp
             * 
             */
            //获取查询条件
            Customer criteria=CommonUtils.toBean(request.getParameterMap(), Customer.class);
            //处理get请求编码问题
            int pc=getPc(request);//得到pc
            int ps=10;//给定ps,10行记录
            PageBean<Customer> pb=customerService.query(criteria,pc,ps);
            
            //得到url,保存到pb中
            pb.setUrl(getUrl(request));
            request.setAttribute("pb",pb);
            return "f:/list.jsp";
        }
        
        public String getUrl(HttpServletRequest request){
            String contextPath=request.getContextPath();//获取项目名
            String servletPath=request.getServletPath();//获取servletPath,即/CustomerServlet
            String queryString=request.getQueryString();//获取问号之后的参数部分
            
            if(queryString.contains("&pc=")){//判断参数部分中是否包含pc这个参数,如果包含就截取
                int index=queryString.lastIndexOf("&pc=");
                queryString=queryString.substring(0,index);
            }
            return contextPath+servletPath+"?"+queryString;
        }
        
        public Customer encoding(Customer criteria) throws UnsupportedEncodingException{
            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;
        }
        
    
        
        
    }
    customerServlet
  • 相关阅读:
    聊一聊正则表达式,最全最常用总结
    11个优秀的Android开发开源项目
    一招教你打造一个滑动置顶的视觉特效
    这些优质的电子书 开发必备【干货精选】
    用Kotlin破解Android版微信小游戏跳一跳
    2017上半年技术文章集合【Android】—184篇文章分类汇总
    经常用到的字符串函数
    EhLib使用说明
    Delphi中本年、本月、本周的第一天和最后天
    Delphi中关于listview的一些使用
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5727351.html
Copyright © 2011-2022 走看看