当前位置: 移动技术网 > IT编程>开发语言>Java > javaWeb核心技术第十二篇之分页和条件

javaWeb核心技术第十二篇之分页和条件

2019年09月01日  | 移动技术网IT编程  | 我要评论
分页:limit ?,?
    参数1 : startindex  开始索引.
    参数2 : pagesize  每页显示的个数
    n 表示第几页 给定一个特殊的单词  pagenumber
    select * from product;
    
    第一页显示五条数据:
    select * from product limit 0 , 5;
    第二页显示五条数据
    select * from product limit 5 , 5;
    第三页显示五条数据
    select * from product limit 10 , 5;
    
    第n页显示五条数据
    select * from product limit (pagenumber-1)*pagesize , pagesize;
    
    如果只有一个参数 表示 第一页 显示几个数据
    select * from product limit 5;
    
    简单分页查询步骤:
        1.sql : select from table limit ?,?
        2.startintdex : 开始索引  不可以是负数
        3.pagesize : 每页显示的个数
        4.pagenumber : 用户访问的当前页
        5.由页面发起传入 pagenumber 和 pagesize(目前写死)  在service层中进行计算startindex
        6.公式 (pagenumber-1)*pagesize
    
    高级分页查询:
        将service返回的六个参数,封装成一个pagebean
    两个传的
        pagenumber,pagesize.
    两个查的
        totalrecord,data
    两个算的
        startindex,totalpage
    
    在service编写代码逻辑 --> 将所有的代码逻辑封装到pagebean中
    
/*
    
    <!--分页  class="disabled"  class="active"-->
        <div style="width:1100px;margin:0 auto;margin-top:50px;">
            
            <ul class="pagination" style="text-align:center; margin-top:10px;">
                
                <%-- 如果当前页 等于 1 不需要再显示上一页  如果当前不等于1 显示 --%>
                <c:if test="${pagebean.pagenumber != 1}">
                    <li ><a href="${pagecontext.request.contextpath}/productservlet?method=findall&pagenumber=1" aria-label="previous"><span aria-hidden="true">&laquo;</span></a></li>
                    <li ><a href="${pagecontext.request.contextpath}/productservlet?method=findall&pagenumber=${pagebean.pagenumber - 1 }" aria-label="previous"><span aria-hidden="true">上一页</span></a></li>
                </c:if>
                
                <%-- 循环显示 所有的页数 --%>
                <c:foreach begin="${pagebean.start}" end="${pagebean.end}" var="num" step="1">
                    <li ${pagebean.pagenumber == num ? " class='active'"  : ""} ><a href="${pagecontext.request.contextpath}/productservlet?method=findall&pagenumber=${num}">${num}</a></li>
                </c:foreach>
                
                <%-- 如果当前页小于总页数 显示下一页 --%>
                <c:if test="${pagebean.pagenumber < pagebean.totalpage}">
                    <li><a href="${pagecontext.request.contextpath}/productservlet?method=findall&pagenumber=${pagebean.pagenumber + 1 }" aria-label="next"><span aria-hidden="true">下一页</span></a></li>
                    <li><a href="${pagecontext.request.contextpath}/productservlet?method=findall&pagenumber=${pagebean.totalpage}" aria-label="next"><span aria-hidden="true">&raquo;</span></a></li>
                </c:if>
                
                
            </ul>
            
        </div>
        <!-- 分页结束=======================        -->
    

    以后专门用来处理分页的数据:
    泛型的定义:
        1:方法级别的定义,修饰和返回值之间<t>
        2:类级别泛型定义,类名后<t>
    public class pagebean<t> {
        /*
        一共六个参数:
        2个传入:
            pagenumber : 表示当前页
            pagesize : 表示每页显示个数
        2个查询
            data : 分页的数据
            totalrecord : 总记录数
        2个计算
            startindex : 开始索引
            totalpage : 总页数
        private int pagenumber;
        private int pagesize;
        private int totalrecodr;
        private int startindex;
        private int totalpage;
        private list<t> data;
        
        public int getstartindex() {
            startindex = (pagenumber - 1)*pagesize;
        }
        
        public int gettotalpage() {
            if(totalrecord % pagesize == 0) {
                totalpage = totalrecord / pagesize;
            }else {
                totalpage = totalrecord / pagesize + 1;
            }
            return totalpage;
        }
        
        public int getpagenumber() {
            return pagenumber;
        }
        
        public void setpagenumber(int pagenumber) {
            this.pagenumber = pagenumber;
        }
    }
    开发中真实案例--前五后四动态条 - 扩展 - 前四后五
        开发中应用:
    //循环的开始
        private int start;
    //循环结束
        private int end;
        
    //计算  开始  和  结束的数据
    private void jisuan() {
        //总页数有没有可能小于10
        //小于 10 不需要前四后五的动态条
        if(gettotalpage() < 10) {//必须调用gettotalpage() 因为totalpage需要提前计算
            start = 1;
            end = totalpage;//最后一页等于最大页数
            
        }else {
            //总页数一定大于10  需要前四后五动态条
            start = pagenumber - 4;
            end = pagenumber + 5;
            //如果start < 1 表示 当前1 2 3 4 总共显示10页
            if(start < 1) {
                start = 1;
                end = 10;
            }
            
            //如果end > totalpage 需要 计算start值
            if(end > totalpage) {
                end = totalpage;
                start = totalpage - 9;
            }
            
        }
        
    }
    
案例:代码体现

    public class productservlet extends httpservlet {
    
    protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    
        try {
            //获得页面传递的参数 用来执行某段代码
            string method = request.getparameter("method");
            
            productservice pservice = new productservice();
            categoryservice cservice = new categoryservice();
            //根据页面功能执行某段特殊的代码
            if("findall".equals(method)){
                /**
                 * 1.类型问题       两种解决方式:   1.正则 2.try
                 * 2.索引不可以是负数
                 */
                //1.获得 
                // 获得分页的数据 pagenumber 
                string pagenumberstr = request.getparameter("pagenumber");            
                int pagenumber = 1;
                try {
                    //如果是a 强转失败  赋值操作没有成功  pagenumber = 1 
                    pagenumber = integer.valueof(pagenumberstr);
                    if(pagenumber < 1 ){
                        pagenumber = 1;
                    }
                    
                } catch (exception e) {
                }
                int pagesize = 2;
                //2.处理
                //list<product> plist = pservice.findbypage(pagenumber , pagesize);
                pagebean<product> pagebean = pservice.findbypage(pagenumber , pagesize);
                //3.响应
                //3.1 将数据存到request
                request.setattribute("pagebean", pagebean);
                //3.2 请求转发给jsp 
                request.getrequestdispatcher("/admin/product/product_list.jsp").forward(request, response);
                return;
            }
            
            //添加商品前查询分类的数据
            if("addproductui".equals(method)){
                //1.获得
                //2.处理
                //2.1 调用service 查询出所有分类 返回值 list<category>
                
                list<category> clist = cservice.findall();
                //3.响应
                //3.1 将数据存到request
                request.setattribute("clist", clist);
                //3.2 请求转发给product_add.jsp 
                request.getrequestdispatcher("/admin/product/product_add.jsp").forward(request, response);
                
                return;
            }
            
            //添加商品数据
            if("addproduct".equals(method)){
                
                //1.获得
                //1.1 获得map
                map<string, string[]> map = request.getparametermap();
                //1.2 创建product
                product product = new product();
                //1.3 封装数据
                beanutils.populate(product, map);
                //1.4 手动封装数据
                product.setpid( uuid.randomuuid().tostring().replace("-", "") );//主键会随机生成
                product.setpimage("products/1/c_0001.jpg");
                product.setpdate(new date().tolocalestring());
                product.setis_hot(0);//0表示非热门
                product.setpflag(0);//0表示未下架
                //2.处理
                //调用service保存
                pservice.save(product);
                //3.响应
                //重定向到查询所有的案例
                response.sendredirect(request.getcontextpath() +"/productservlet?method=findall");
                return;
                
            }
            
            //根据pid查询出商品的信息
            if("findbypid".equals(method)){
                //1.获得
                //获得pid的编号
                string pid = request.getparameter("pid");
                //2 处理
                //2.1 商品数据
                product product = pservice.findbypid(pid);
                //2.2 分类的数据
                list<category> clist = cservice.findall();
                //3 响应
                request.setattribute("product", product);
                request.setattribute("clist", clist);
                request.getrequestdispatcher("/admin/product/product_edit.jsp").forward(request, response);
                return;
            }
            
            
            //修改商品数据的代码
            if("editproduct".equals(method)){
                //1.获得
                //1.1 获得map集合
                map<string, string[]> map = request.getparametermap();
                //1.2 创建product对象
                product product = new product();
                //1.3 封装
                beanutils.populate(product, map);
                //2.处理
                //2.1 调用service修改
                boolean flag = pservice.update(product);
                //3.响应
                //3.1 重定向到查询所有的案例
                if(flag){
                    //成功
                    response.sendredirect(request.getcontextpath() + "/productservlet?method=findall");
                }
                return ;
            }
            
            
            //根据pid删除商品
            if("deletebypid".equals(method)){
                //1.获得
                //获得pid
                string pid = request.getparameter("pid");
                //2.处理
                int count = pservice.deletebypid(pid);
                //3.响应
                if(count > 0){
                    response.sendredirect(request.getcontextpath() + "/productservlet?method=findall");
                }
                return;
            }
            
        } catch (exception e) {
            e.printstacktrace();
        }
    
    }

    protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
        // todo auto-generated method stub
        doget(request, response);
    }
    
    
    public static void main(string[] args) {
        system.out.println(uuid.randomuuid().tostring().replace("-", ""));
        
    }

}

public class productservice {
    
    
    /*public pagebean<product> findbypage(int pagenumber, int pagesize) throws sqlexception {
        //创建一个即将被返回的对象 pagebean<product>
        pagebean<product> pagebean = new pagebean<product>();
        
        
        productdao dao = new productdao();
        
        //将pagenumber 转换成startindex
        int startindex = (pagenumber - 1) * pagesize;
        
        //查询当前页的2条数据
        list<product> data = dao.findbypage( startindex, pagesize);
        
        
        //查询总记录数
        int totalrecord = dao.findrecord();
        
        //计算总页数
        int totalpage = 0;
        if(totalrecord % pagesize == 0 ){
            totalpage = totalrecord / pagesize;
        }else{
            totalpage = totalrecord / pagesize + 1;
        }
        
        //赋值
        pagebean.setdata(data);
        pagebean.setpagenumber(pagenumber);
        pagebean.setpagesize(pagesize);
        pagebean.setstartindex(startindex);
        pagebean.settotalpage(totalpage);
        pagebean.settotalrecord(totalrecord);
        return pagebean;
    }*/
    public pagebean<product> findbypage(int pagenumber, int pagesize) throws sqlexception {
        //创建一个即将被返回的对象 pagebean<product>
        pagebean<product> pagebean = new pagebean<product>( pagenumber , pagesize);
        
        productdao dao = new productdao();
        
        //查询当前页的2条数据
        list<product> data = dao.findbypage( pagebean.getstartindex() , pagesize);
        
        //查询总记录数
        int totalrecord = dao.findrecord();
        
        //赋值
        pagebean.setdata(data);
        pagebean.settotalrecord(totalrecord);
        return pagebean;
    }

    public list<product> findall() throws sqlexception {
        productdao dao = new productdao();
        return dao.findall();
    }

    public void save(product product) throws sqlexception {
        productdao dao = new productdao();
         dao.save(product);
    }

    public product findbypid(string pid) throws sqlexception {
        productdao dao = new productdao();
        return  dao.findbypid(pid);
    }

    public boolean update(product product) throws sqlexception {
        productdao dao = new productdao();
        return  dao.update(product);
    }

    public int deletebypid(string pid) throws sqlexception {
        productdao dao = new productdao();
        return dao.deletebypid(pid);
    }

    

}

package com.baidu.domain;

public class product {

     /* 
      `pid` varchar(32) not null,
      `pname` varchar(50) default null,        #商品名称
      `market_price` double default null,    #商场价
      
      `shop_price` double default null,        #商城价
      `pimage` varchar(200) default null,    #商品图片路径
      `pdate` date default null,            #上架时间
      
      `is_hot` int(11) default null,        #是否热门:0=不热门,1=热门
      `pdesc` varchar(255) default null,    #商品描述
      `pflag` int(11) default 0,            #商品标记:0=未下架(默认值),1=已经下架
      
      `cid` varchar(32) default null,        #分类id*/
    
    private string pid;
    private string pname;
    private double market_price;
    
    private double shop_price;
    private string pimage;
    private string pdate;
    
    private int is_hot;
    private string pdesc;
    private int pflag;
    
    private string cid;

    public string getpid() {
        return pid;
    }

    public void setpid(string pid) {
        this.pid = pid;
    }

    public string getpname() {
        return pname;
    }

    public void setpname(string pname) {
        this.pname = pname;
    }

    public double getmarket_price() {
        return market_price;
    }

    public void setmarket_price(double market_price) {
        this.market_price = market_price;
    }

    public double getshop_price() {
        return shop_price;
    }

    public void setshop_price(double shop_price) {
        this.shop_price = shop_price;
    }

    public string getpimage() {
        return pimage;
    }

    public void setpimage(string pimage) {
        this.pimage = pimage;
    }

    public string getpdate() {
        return pdate;
    }

    public void setpdate(string pdate) {
        this.pdate = pdate;
    }

    public int getis_hot() {
        return is_hot;
    }

    public void setis_hot(int is_hot) {
        this.is_hot = is_hot;
    }

    public string getpdesc() {
        return pdesc;
    }

    public void setpdesc(string pdesc) {
        this.pdesc = pdesc;
    }

    public int getpflag() {
        return pflag;
    }

    public void setpflag(int pflag) {
        this.pflag = pflag;
    }

    public string getcid() {
        return cid;
    }

    public void setcid(string cid) {
        this.cid = cid;
    }
    
    
    
    
}

public class productdao {
    /**
     * 分页的dao
     * @param startindex
     * @param pagesize
     * @return
     * @throws sqlexception 
     */
    public list<product> findbypage(int startindex, int pagesize) throws sqlexception {
        queryrunner queryrunner = new queryrunner(c3p0utils.getdatasource());
        string sql =" select * from product limit ?,? ";
        object [] params = {
                startindex , pagesize
        };
        return queryrunner.query(sql, new beanlisthandler<product>(product.class), params);
    }
    /**
     * 计算总记录数
     * @return
     * @throws sqlexception 
     */
    public int findrecord() throws sqlexception {
        queryrunner queryrunner = new queryrunner(c3p0utils.getdatasource());
        string sql =" select count(*) from product ";
        object [] params = {
        };
        object object = queryrunner.query(sql, new scalarhandler(), params);
        return integer.valueof(object.tostring());
    }    

    public list<product> findall() throws sqlexception {
        queryrunner queryrunner = new queryrunner(c3p0utils.getdatasource());
        
        string sql =" select * from product order by pdate desc ";
        
        object [] params = {};
        
        return queryrunner.query(sql, new beanlisthandler<product>(product.class), params);
    }

    public void save(product product) throws sqlexception {
        queryrunner queryrunner = new queryrunner(c3p0utils.getdatasource());
        
        string sql =" insert into product values(?,?,?,?,?,?,?,?,?,?) ";
        
        object [] params = {
                product.getpid() , product.getpname() , product.getmarket_price() , 
                product.getshop_price() , product.getpimage() , product.getpdate() , 
                product.getis_hot() , product.getpdesc() , product.getpflag() , 
                product.getcid()
        };
        
        queryrunner.update(sql, params);
    }

    public product findbypid(string pid) throws sqlexception {
        queryrunner queryrunner = new queryrunner(c3p0utils.getdatasource());
        
        string sql =" select * from product where pid = ? ";
        
        object [] params = {pid};
        
        return queryrunner.query(sql, new beanhandler<product>(product.class), params);
    }

    public boolean update(product product) throws sqlexception {
        
        queryrunner queryrunner = new queryrunner(c3p0utils.getdatasource());
        
        string  sql = " update product set pname = ? , shop_price = ? , pdesc = ? , cid = ? where pid = ?  ";
        
        object [] params = {
                product.getpname() , product.getshop_price() , product.getpdesc() , 
                product.getcid() , product.getpid()
        };
        
        
        
        return queryrunner.update(sql, params) > 0 ;
    }

    public int deletebypid(string pid) throws sqlexception {

        queryrunner queryrunner = new queryrunner(c3p0utils.getdatasource());
        
        string  sql = " delete from product where pid = ?  ";
        
        object [] params = {
                pid
        };
        
        
        
        return queryrunner.update(sql, params)  ;
    }
    
/**
 * 处理乱码的工具类
 *
 */
public class encodingfilter implements filter {


    public void destroy() {
        // todo auto-generated method stub
    }

    public void dofilter(servletrequest req, servletresponse resp, filterchain chain) throws ioexception, servletexception {
        final httpservletrequest request = (httpservletrequest)req;
        httpservletresponse response = (httpservletresponse)resp;
        try {
            
            //处理post乱码
            request.setcharacterencoding("utf-8");
            
            //处理响应
            response.setheader("content-type", "text/html;charset=utf-8");
            
            //处理get乱码
            httpservletrequest myrequest = (httpservletrequest)proxy.newproxyinstance(
                    encodingfilter.class.getclassloader(), 
                    request.getclass().getinterfaces(), 
                    new invocationhandler() {
                        @override
                        public object invoke(object proxy, method method, object[] args) throws throwable {
                            
                            //可以对getparameter进行增强   get提交方式
                            
                            //1.判断是get请求方式
                            string requestmethod= request.getmethod();
                            if("get".equalsignorecase(requestmethod)){
                                //get提交  只对getparameter方法进行拦截
                                string methodname = method.getname();
                                if("getparameter".equals(methodname)){
                                    //get方式 并且 调用的getparameter方法
                                    //获得以前乱码 return 不乱码
                                    string tempvalue = request.getparameter(args[0].tostring());
                                    //如果没有获得数据 防止空指针
                                    if(tempvalue == null){
                                        return null;
                                    }
                                    return new string(tempvalue.getbytes("iso-8859-1"),"utf-8");
                                    
                                }
                            }
                            
                            //不需要增强
                            return method.invoke(request, args);
                        }
                    });
            
            //放行
            chain.dofilter(myrequest, response);
        } catch (exception e) {
            // todo auto-generated catch block
            e.printstacktrace();
        }
    }
    public void init(filterconfig fconfig) throws servletexception {
        // todo auto-generated method stub
    }

}

jsp代码:
    <%-- 获得数据 并遍历 --%>
                                <c:foreach items="${pagebean.data}" var="product">
                                    <tr onmouseover="this.style.backgroundcolor = '#f5fafe'"
                                        onmouseout="this.style.backgroundcolor = '#fff';">
                                        <td style="cursor: hand; height: 22px" align="center">
                                            <input type="checkbox" name="" value="" />
                                        </td>
                                        <td style="cursor: hand; height: 22px" align="center">
                                            <img src="${pagecontext.request.contextpath}/${product.pimage}" style="height: 200px;width:150px" />
                                        </td>
                                        <td style="cursor: hand; height: 22px" align="center">
                                            ${product.cid}
                                        </td>
                                        <td style="cursor: hand; height: 22px" align="center">
                                            ${product.pname}
                                        </td>
                                        <td style="cursor: hand; height: 22px" align="center">
                                            ${product.shop_price}
                                        </td>
                                        <td style="cursor: hand; height: 22px" align="center">
                                            ${product.pdesc}
                                        </td>
                                        <td align="center" style="height: 22px">
                                            <%--编辑 --%>
                                            <a href="${pagecontext.request.contextpath}/productservlet?pid=${product.pid}&method=findbypid">
                                                <img src="${pagecontext.request.contextpath}/images/i_edit.gif" border="0" style="cursor: hand">
                                            </a>
                                        </td>
                                        <td align="center" style="height: 22px">
                                            <%--查询 --%>
                                            <a href="../user/view.html?userid=15">
                                                <img src="${pagecontext.request.contextpath}/images/button_view.gif" border="0" style="cursor: hand">
                                            </a>
                                        </td>
                                        <td align="center" style="height: 22px">
                                            <%--删除  ctrl + q --%>
                                            <a href="${pagecontext.request.contextpath}/productservlet?method=deletebypid&pid=${product.pid}">
                                                <img src="${pagecontext.request.contextpath}/images/i_del.gif" width="16" height="16" border="0" style="cursor: hand">
                                            </a>
                                            
                                            
                                            <%--提示删除 --%>
                                            <a href="javascript:void(0)" onclick="deletebypid('${product.pid}')">
                                                <img src="${pagecontext.request.contextpath}/images/i_del.gif" width="16" height="16" border="0" style="cursor: hand">
                                            </a>
                                        </td>
                                            
                                    </tr>
                                </c:foreach>
                                <%-- 获得数据 并遍历 --%>
                                <script>
                                    //javascript 需要在写在 header标签中
                                    function deletebypid(pid){
                                        //alert(pid);
                                        //提示用户 
                                        var flag = confirm("您确定要删除信息吗?");
                                        if(flag){
                                            //确定删除
                                            //访问服务器删除的servlet
                                            //修改地址栏 跳转路径  等效我们自己点击超链接
                                            location.href="${pagecontext.request.contextpath}/productservlet?method=deletebypid&pid="+pid;
                                        }
                                    }
                                </script>
                        </table>
                    </td>
                </tr>
            </tbody>
        </table>
        <!--分页  class="disabled"  class="active"-->
        <div style="width:1100px;margin:0 auto;margin-top:50px;">
            
            <ul class="pagination" style="text-align:center; margin-top:10px;">
                
                <%-- 如果当前页 等于 1 不需要再显示上一页  如果当前不等于1 显示 --%>
                <c:if test="${pagebean.pagenumber != 1}">
                    <li ><a href="${pagecontext.request.contextpath}/productservlet?method=findall&pagenumber=1" aria-label="previous"><span aria-hidden="true">&laquo;</span></a></li>
                    <li ><a href="${pagecontext.request.contextpath}/productservlet?method=findall&pagenumber=${pagebean.pagenumber - 1 }" aria-label="previous"><span aria-hidden="true">上一页</span></a></li>
                </c:if>
                
                <%-- 循环显示 所有的页数 --%>
                <c:foreach begin="${pagebean.start}" end="${pagebean.end}" var="num" step="1">
                    <li ${pagebean.pagenumber == num ? " class='active'"  : ""} ><a href="${pagecontext.request.contextpath}/productservlet?method=findall&pagenumber=${num}">${num}</a></li>
                </c:foreach>
                
                <%-- 如果当前页小于总页数 显示下一页 --%>
                <c:if test="${pagebean.pagenumber < pagebean.totalpage}">
                    <li><a href="${pagecontext.request.contextpath}/productservlet?method=findall&pagenumber=${pagebean.pagenumber + 1 }" aria-label="next"><span aria-hidden="true">下一页</span></a></li>
                    <li><a href="${pagecontext.request.contextpath}/productservlet?method=findall&pagenumber=${pagebean.totalpage}" aria-label="next"><span aria-hidden="true">&raquo;</span></a></li>
                </c:if>
                
                
            </ul>
            
        </div>
        <!-- 分页结束=======================        -->


    
    条件查询:
        1: 先在首页上查询分类数据,并且遍历显示
            分析:
                select * from product where cid = ? and pname = ?;
                含有的可能性:
                    1.两者都有.
                    2.两者都没有.
                    3.有cid但没有pname
                    4.没有cid但有pname
                
                select count(*) from product where 1=1;
                伪代码:
                    sql = " select * from product where 1=1 ";
                    if(cid != null) {
                        sql += " and cid = ? "
                    }
                    if(pname != null) {
                        sql += " and pname like ? "
                    }
        1: 修改表单 action属性,method属性,name属性,自定义的method判断逻辑.
        2: 调用servlet
            a : 获得 cid和pname
            b : 处理 调用service 调用dao(重要)
            c : 响应 - 将数据存到request里,请求转发给product_list.jsp
        3.对jsp页面进行改造
        
    条件查询注意事项:
        1 . dao的sql部分,拼接的问题,使用 where 1=1 解决了脏读、不可重复读、
        2 . dao的参数拼接部分,使用list接收数据,最后将list转换成数组,解决.
        3 . 查询完以后将数据返回给页面,但还需要加上,用户传入后台的cid和pname;
    切记:条件查询 不可以 和 分页 同一个项目 但以后 条件查询需要和分页结合
        4 . 如果条件查询和分页需要做到同一个项目,需要处理参数问题.
        5 . pagebean 查询总记录数 --> 如果加入条件查询,查询总记录数时需要加上条件.
    
案例:代码体现
    public class productservlet extends httpservlet {
    
    protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    
        try {
            //获得页面传递的参数 用来执行某段代码
            string method = request.getparameter("method");
            
            productservice pservice = new productservice();
            categoryservice cservice = new categoryservice();
            //根据页面功能执行某段特殊的代码
            if("findall".equals(method)){
                //执行查询所有的代码
                //1.获得
                //1.31 获得cid
                string cid = request.getparameter("cid");
                //1.2 获得pname
                string pname = request.getparameter("pname");
                
                
                //2.处理
                list<product> plist = pservice.findall( cid , pname );
                list<category> clist = cservice.findall();
                //3.响应
                //3.1 将数据存到request
                request.setattribute("plist", plist);
                request.setattribute("clist", clist);
                
                request.setattribute("cid", cid);
                request.setattribute("pname", pname);
                
                //3.2 请求转发给jsp 
                request.getrequestdispatcher("/admin/product/product_list.jsp").forward(request, response);
                return;
            }

public class productdao {
    /**
     * 条件查询
     * @param cid
     * @param pname
     * @return
     * @throws sqlexception 
     */
    public list<product> findall(string cid, string pname) throws sqlexception {
        queryrunner queryrunner = new queryrunner(c3p0utils.getdatasource());
        
        string  sql = " select * from product where 1=1 ";
        
        //定义一个list  作用 用来保存参数 
        list<object> paramlist = new arraylist<object>();
        //cid判断
        if(cid != null && !"".equals(cid)){
            sql += " and cid = ?  ";
            paramlist.add(cid);
        }
        //pname判断
        if(pname != null && !"".equals(pname)){
            sql += " and pname like ?  ";
            paramlist.add("%"+pname+"%");
        }
        
        //数组的缺陷 长度固定  集合的长度不固定   集合最后转换成数组
        object [] params = paramlist.toarray();
        
        return queryrunner.query(sql,new beanlisthandler<product>(product.class), params);
        
    }
    
    <form action="${pagecontext.request.contextpath}/productservlet" method="post">
                            <%--隐藏域 --%>
                            <input type="hidden" name="method" value="findall"/>
                        
                            <table cellpadding="0" cellspacing="0" border="0" width="100%">
                                <tr>
                                    <td height="22" align="center" bgcolor="#f5fafe" class="ta_01" style="width: 15%">
                                        分类
                                    </td>
                                    <td class="ta_01" bgcolor="#ffffff" style="width: 30%">
                                        <select name="cid" class="form-control">
                                            <option value="">请选择</option>
                                            <c:foreach items="${clist}" var="category">
                                                <option ${category.cid==cid ? "selected" : ""} value="${category.cid}">${category.cname}</option>
                                            </c:foreach>
                                        </select>
                                    </td>
                                    <td height="22" align="center" bgcolor="#f5fafe" class="ta_01" style="width: 15%">
                                        商品名称:
                                    </td>
                                    <td class="ta_01" bgcolor="#ffffff">
                                        <input type="text" name="pname" size="15" value="${pname}" class="form-control"/>
                                    </td>
            
    
    批量删除:
        思想:
            前台两套方法:
                1 . 表单提交:将所有被选中的数据,的pid传入后台,后台执行批量删除.
                2 . 修改sql 修改成 sql=" delete from product where pid in (?) " 数据循环拼接 1,2,4
                3 . 开发中会使用jdbc jdbc当中有批处理,也可以处理批量任务.
        
            事务特性:
                a : 原子性;
                c : 一致性;
                i : 隔离性 : isolation 隔离会产生隔离问题
                d : 持久性.

    protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    
        try {
            //获得页面传递的参数 用来执行某段代码
            string method = request.getparameter("method");
            
            productservice pservice = new productservice();
            categoryservice cservice = new categoryservice();
            //根据pid删除商品
            if("deletebypid".equals(method)){
                //1.获得
                //获得数组集合
                string[] pids = request.getparametervalues("pid");
                //2.处理
                int count = pservice.deletebypid(pids);
                //3.响应
                if(count > 0){
                    response.sendredirect(request.getcontextpath() + "/productservlet?method=findall");
                }
                return;
            }
            
    <td align="center" width="6%">
                                    <input type="button" value="删除选中" onclick="deleteall()">
                                    <script>
                                        function deleteall(){
                                            //1.提示
                                            var flag = confirm("您确定要删除信息吗?");
                                            if(!flag){
                                                return ; 
                                            }
                                            //2.获得所有选中的pid 获得所有的数组 最后的格式 pid=1&pid=2&pid3..
                                            var pids = $("input[name='pid']:checked").serialize() ;
                                            //3.发送
                                            location.href="${pagecontext.request.contextpath}/productservlet?method=deletebypid&"+pids;
                                        }
                                    </script>
                                </td>
                                <td align="center" width="15%">
                                    预览图
                                </td>
                                <td align="center" width="12%">
                                    商品分类
                                </td>
                                <td align="center" width="25%">
                                    商品名称
                                </td>
                                <td align="center" width="8%">
                                    商品价格
                                </td>
                                <td width="11%" align="center">
                                    描述
                                </td>
                                <td width="7%" align="center">
                                    编辑
                                </td>
                                <td width="7%" align="center">
                                    查看
                                </td>
                                <td width="7%" align="center">
                                    删除
                                </td>
                            </tr>
                                <%-- 获得数据 并遍历 --%>
                                <c:foreach items="${plist}" var="product">
                                    <tr onmouseover="this.style.backgroundcolor = '#f5fafe'"
                                        onmouseout="this.style.backgroundcolor = '#fff';">
                                        <td style="cursor: hand; height: 22px" align="center">
                                            <input type="checkbox" name="pid" value="${product.pid}" />
                                        </td>
                                        <td style="cursor: hand; height: 22px" align="center">
                                            <img src="${pagecontext.request.contextpath}/${product.pimage}" style="height: 200px;width:150px" />
                                        </td>
                                        <td style="cursor: hand; height: 22px" align="center">
                                            ${product.cid}
                                        </td>
                                        <td style="cursor: hand; height: 22px" align="center">
                                            ${product.pname}
                                        </td>
                                        <td style="cursor: hand; height: 22px" align="center">
                                            ${product.shop_price}
                                        </td>
                                        <td style="cursor: hand; height: 22px" align="center">
                                            ${product.pdesc}
                                        </td>
                                        <td align="center" style="height: 22px">
                                            <%--编辑 --%>
                                            <a href="${pagecontext.request.contextpath}/productservlet?pid=${product.pid}&method=findbypid">
                                                <img src="${pagecontext.request.contextpath}/images/i_edit.gif" border="0" style="cursor: hand">
                                            </a>
                                        </td>
                                        <td align="center" style="height: 22px">
                                            <%--查询 --%>
                                            <a href="../user/view.html?userid=15">
                                                <img src="${pagecontext.request.contextpath}/images/button_view.gif" border="0" style="cursor: hand">
                                            </a>
                                        </td>
                                        <td align="center" style="height: 22px">
                                            <%--删除  ctrl + q --%>
                                            <a href="${pagecontext.request.contextpath}/productservlet?method=deletebypid&pid=${product.pid}">
                                                <img src="${pagecontext.request.contextpath}/images/i_del.gif" width="16" height="16" border="0" style="cursor: hand">
                                            </a>
                                            
                                            
                                            <%--提示删除 --%>
                                            <a href="javascript:void(0)" onclick="deletebypid('${product.pid}')">
                                                <img src="${pagecontext.request.contextpath}/images/i_del.gif" width="16" height="16" border="0" style="cursor: hand">
                                            </a>
                                        </td>
                                            
                                    </tr>
                                </c:foreach>
                                <%-- 获得数据 并遍历 --%>
                                <script>
                                    //javascript 需要在写在 header标签中
                                    function deletebypid(pid){
                                        //alert(pid);
                                        //提示用户 
                                        var flag = confirm("您确定要删除信息吗?");
                                        if(flag){
                                            //确定删除
                                            //访问服务器删除的servlet
                                            //修改地址栏 跳转路径  等效我们自己点击超链接
                                            location.href="${pagecontext.request.contextpath}/productservlet?method=deletebypid&pid="+pid;
                                        }
                                    }
                                </script>
                        </table>
                    </td>
                </tr>
            </tbodjy>
        </table>
        
数据库开启手动提交以后,只要commit以后,会改成自动提交.查一下是否改成了自动提交

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网