java-web项目的分页与联合模糊查询(不使用分页框架)

来源:互联网 发布:淘宝更换支付宝账户 编辑:程序博客网 时间:2024/06/04 19:43

记录分页的一种实例解决方案:
项目背景:书籍后台管理系统
项目数据库:mysql
项目框架:spring、spring-mvc、mybatis
开发模式:三层架构(controller层、service层、dao层)

一、准备工作-dto类

1.接收内容的实体类-Sold.java:```package com.bookstore.dto;import java.util.Date;public class Sold {private int userid;private int bookid;private String uname;private String bname;private int number = 1;private Date time;private Date beginDate;//联合查询的开始时间private Date endDate;//联合查询的结束时间private int startPage;//翻页时的开始内容位置private int endPage;//翻页时的结束内容位置private double price;private double allprice;private String author;private String press;}```//注:此实体类仅写出参数(其他有参无参自己脑补下就好了ー( ̄~ ̄)ξ)    2.翻页用的实体类-Paging.java:```package com.bookstore.dto;public class Paging {    //也可以将此类参数定义为private    public int currentPage = 1;//当前页    public int rowsPage = 10;//每页显示数    public int allCount;//总记录数    public int maxPage;//总页数    //这是一个根据前台页面传递过来的页面数计算显示内容起始位置的方法    public void getPage(int currentPage,Sold sold){        int start = (currentPage - 1)*rowsPage;        sold.setStartPage(start);        sold.setEndPage(rowsPage);        System.out.println("起始页:"+start);    }}```

二、jsp页面的主要内容
注:jsp添加了此头文件以获取当前页面地址

```    <%    //获取当前系统路径    String path = request.getContextPath();    // 获取当前协议名(默认http) 获取浏览器显示的主机名  获取服务器端口号    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ path + "/";    %>  ```1、联合模糊查询模块:```<tr>  <td>  <form action="<%=basePath %>manager/selectSold.action" method="post">      <table style="font-size: 16px;">      <tr>          <td align=left>用户名</td>          <td><input type="text" name="uname" value="${uname}"/></td>      </tr>      <tr>          <td align=left>开始日期 </td>          <td>          <input type="text" name="beginDate" value="${beginDate}"/>          </td>           <td align=left>结束日期 </td>          <td>          <input type="text" name="endDate" value="${endDate}"/></td>          <td><input type=submit value="查询"/></td>      </tr>      </table>  </form>  </td></tr>```2.内容显示模块与翻页:```<table border="1" width=100%>        <tr>           <td>用户名</td>           <td>书名--购买数量(本)</td>           <td>书单价</td>           <td>出版社</td>           <td>作者</td>           <td>购买日期</td>           <td>总付款</td>       </tr>        <c:forEach var="br" items="${records}">          <tr>            <td>${br.uname}</td>            <td>${br.bname}--${br.number}</td>            <td>${br.price}</td>            <td>${br.press}</td>            <td>${br.author}</td>            <td>${br.time}</td>            <td>${br.allprice}</td>          </tr>         </c:forEach>        <tr>        <td>        <table id="tblTurnPage">                            <tr>                <td>总记录数:${allCount}</td>                 <td>总页数:${maxPage}</td>                <td>当前页:${currentPage}</td>                <td>                <a href="<%=basePath%>manager/turnPage.action?currentPage=1&maxPage=${maxPage}">首页</a>                <a href="<%=basePath%>manager/turnPage.action?currentPage=${currentPage-1}&maxPage=${maxPage}">≮前页</a>                <a href="<%=basePath%>manager/turnPage.action?currentPage=${currentPage+1}&maxPage=${maxPage}">后页≯</a>                <a href="<%=basePath%>manager/turnPage.action?currentPage=${maxPage}&maxPage=${maxPage}">末页</a>                </td>            </tr>                       </table>                    </td>      </tr>    </table> ```

三、controller主要方法体

1、这是controller的开头

@Controller@RequestMapping("/manager/")public class ManagerAction {    //连接service层    private ManagerBiz managerbiz = (ManagerBiz) BeansContainer.getContext().getBean("managerBiz");    //实例化翻页类    private Paging pa=new Paging();

2、联合查询form表单提交到此方法

    /**     * 购买记录页面联合查询     * @param pa     * @param sold     * @param model     * @param request     * @return     * @throws ParseException     */    @RequestMapping(value="selectSold.action",method=RequestMethod.POST)    public String selectSold(Sold sold,HttpServletRequest request) throws ParseException{        System.out.println("联合查询");        allPage(sold,request);        return "buyRecord";    }

3、点击翻页(上下页、首尾页)时进入此方法

/**     * 购买记录页面翻页查询     * @param currentPage     * @param model     * @param request     * @return     */    @RequestMapping(value="turnPage.action",method=RequestMethod.GET)    public String turnPage(Integer currentPage,Integer maxPage,Model model,HttpServletRequest request){        System.out.println("\r\n翻了个页");        Sold sold = (Sold) request.getSession().getAttribute("sold");        if(currentPage < 1){            currentPage = 1;        }        if(currentPage > maxPage){            currentPage = maxPage;        }        allCount(currentPage,sold,request);        return "buyRecord";    }

4、方法体,根据条件查询需要展示的所有记录的条数,并计算最大页数

public void allPage(Sold sold,HttpServletRequest request){        System.out.println("\r\n模糊查询记录总数:" + sold.getUname() + sold.getBeginDate() + sold.getEndDate() );        int allCount = managerbiz.allCount(sold);        int maxPage = (allCount/pa.rowsPage);        if((allCount%pa.rowsPage > 0)){            maxPage += 1;        }        request.getSession().setAttribute("allCount",allCount);        request.getSession().setAttribute("maxPage",maxPage);        allCount(1,sold,request);    }

5、主要查询方法,获得list集合反馈给页面

/**     * 出售记录查询方法体     * @param sold     * @param pa     * @param model     */    public void allCount(Integer currentPage,Sold sold,HttpServletRequest request){        System.out.println("模糊查询出售记录:" + currentPage + sold.getUname() + sold.getBeginDate() + sold.getEndDate());        //计算开始页与每页显示条数        pa.getPage(currentPage,sold);        List<Sold> li = managerbiz.selectSold(sold);        request.setAttribute("records", li);        request.getSession().setAttribute("currentPage", currentPage);        request.getSession().setAttribute("sold", sold);    }

四、service层、dao层与mapper接口

1、service层:
@Service("managerBiz")public class ManagerBiz {    //连接dao层    @Autowired    private ManagerDao managerdao;//分页    public int allCount(Sold sold){        return managerdao.allCount(sold);    }    public List<Sold> selectSold(Sold sold){        return managerdao.selectSold(sold);    }
2、dao层:
@Repository("managerDao")public class ManagerDao {    //连接mapper接口    @Autowired    private Mapper mapper;        //分页    public int allCount(Sold sold){        return mapper.allCount(sold);    }    public List<Sold> selectSold(Sold sold){        return mapper.selectSold(sold);    }
3、mapper接口
public interface Mapper {    //分页    public int allCount(Sold sold);    public List<Sold> selectSold(Sold sold);}

五、mapper.xml(mybatis)(关键

注:所有表均为mysql bs_sold为出售记录表 bs_book为书籍表 bs_user为用户表 bs_press为出版社表1、查询总内容数量:
<select id="allCount" resultType="int">    select count(1) from bs_sold s,bs_book b,bs_user u,bs_press p    where s.bookid = b.id and s.userid = u.id and b.pressid = p.id         <if test="uname != null and uname != ''">            //根据用户名进行模糊查询            and u.uname like concat('%',#{uname},'%')        </if>         <if test="beginDate != null">            and s.time >= #{beginDate}        </if>        <if test="endDate != null">            and #{endDate} >= s.time        </if></select>
2、查询记录内容:
<select id="selectSold" resultType="com.bookstore.dto.Sold">    select s.number,s.price,s.time,s.allprice,u.uname,b.bname,b.author,p.press     from bs_sold s,bs_book b,bs_user u,bs_press p    where s.bookid = b.id and s.userid = u.id and b.pressid = p.id and     (select time from bs_sold s,bs_user u where s.userid = u.id        <if test="uname != null and uname != ''">            and u.uname like concat('%',#{uname},'%')        </if>         <if test="beginDate != null">            and s.time >= #{beginDate}        </if>        <if test="endDate != null">            and #{endDate} >= s.time        </if>        //order by为排序        order by s.time desc        //limit为mysql分页方法        limit #{startPage},1    ) >= s.time         order by s.time desc        limit #{endPage}</select>
3、mysql的limit分页方法:limit x,yx:查询记录开始位置,y:查询记录数量,1便是仅查询一条数据,limit查询从0开始计算limit x 方法等同于 limit 0,x①、普通查询方案:劣势:查询速度较慢
//从第十一条记录开始查询,总共查询十条select * from book limit 10,10
②、优化方案:优势:查询速度快
//从第十一条记录开始查询,总共查十条select * from     (select * from book limit 10,1)    limit 10

总了个结:
思考分页的写法还是非常有趣的,主要是分页的逻辑理顺,会好写很多。
感觉还有很多很好的方法,求各位大佬指点。

原创粉丝点击