网上图书商城项目学习笔记-011Book模块查询(分页)
2016-01-27 14:59
501 查看
一、流程分析
1.图书模块
2.分布分析
二、代码
1.view层
1)list.jsp
2)pager.jsp
2.servlet层
1)BookServlet.java
3.service层
1)BookService.java
4.dao层
1)BookDao.java
1.图书模块
2.分布分析
二、代码
1.view层
1)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"> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <link rel="stylesheet" type="text/css" href="<c:url value='/jsps/css/book/list.css'/>"> <link rel="stylesheet" type="text/css" href="<c:url value='/jsps/pager/pager.css'/>" /> <script type="text/javascript" src="<c:url value='/jsps/pager/pager.js'/>"></script> <script type="text/javascript" src="<c:url value='/jquery/jquery-1.5.1.js'/>"></script> <script type="text/javascript" src="<c:url value='/jsps/js/book/list.js'/>"></script> </head> <body> <ul> <c:forEach items="${pb.beanList }" var="book"> <li> <div class="inner"> <a class="pic" href="<c:url value='/BookServlet?method=load&bid=${book.bid }'/>"><img src="<c:url value='/${book.image_b }'/>" border="0"/></a> <p class="price"> <span class="price_n">¥${book.currPrice }</span> <span class="price_r">¥${book.price }</span> (<span class="price_s">${book.discount }折</span>) </p> <p><a id="bookname" title="${book.bname }" href="<c:url value='/jsps/book/desc.jsp'/>">${book.bname }</a></p> <%-- url标签会自动对参数进行url编码 --%> <c:url value="/BookServlet" var="authorUrl"> <c:param name="mehtod" value="findByAuthor" /> <c:param name="author" value="${book.author }" /> </c:url> <c:url value="/BookServlet" var="pressUrl"> <c:param name="mehtod" value="findByPress"/> <c:param name="press" value="${book.press }"/> </c:url> <p><a href="<c:url value='${authorUrl }'/>" name='P_zz' title='${book.author }'>${book.author }</a></p> <p class="publishing"> <span>出 版 社:</span><a href="<c:url value='${pressUrl }'/>">${book.press }</a> </p> <p class="publishing_time"><span>出版时间:</span>${book.publishtime }</p> </div> </li> </c:forEach> <!-- <li> <div class="inner"> <a class="pic" href="<c:url value='/jsps/book/desc.jsp'/>"><img src="<c:url value='/book_img/23254532-1_b.jpg'/>" border="0"/></a> <p class="price"> <span class="price_n">¥40.7</span> <span class="price_r">¥50.9</span> (<span class="price_s">6.9折</span>) </p> <p><a id="bookname" title="Spring实战(第3版)(In Action系列中最畅销的Spring图书,近十万读者学习Spring的共同选择)" href="<c:url value='/jsps/book/desc.jsp'/>">Spring实战(第3版)(In Action系列中最畅销的Spring图书,近十万读者学习Spring的共同选择)</a></p> <p><a href="<c:url value='/jsps/book/list.jsp'/>" name='P_zz' title='Craig Walls'>Craig Walls</a></p> <p class="publishing"> <span>出 版 社:</span><a href="<c:url value='/jsps/book/list.jsp'/>">人民邮电出版社</a> </p> <p class="publishing_time"><span>出版时间:</span>2013-06-01</p> </div> </li> <li> <div class="inner"> <a class="pic" href="<c:url value='/jsps/book/desc.jsp'/>"><img src="<c:url value='/book_img/23254532-1_b.jpg'/>" border="0"/></a> <p class="price"> <span class="price_n">¥40.7</span> <span class="price_r">¥50.9</span> (<span class="price_s">6.9折</span>) </p> <p><a id="bookname" title="Spring实战(第3版)(In Action系列中最畅销的Spring图书,近十万读者学习Spring的共同选择)" href="<c:url value='/jsps/book/desc.jsp'/>">Spring实战(第3版)(In Action系列中最畅销的Spring图书,近十万读者学习Spring的共同选择)</a></p> <p><a href="<c:url value='/jsps/book/list.jsp'/>" name='P_zz' title='Craig Walls'>Craig Walls</a></p> <p class="publishing"> <span>出 版 社:</span><a href="<c:url value='/jsps/book/list.jsp'/>">人民邮电出版社</a> </p> <p class="publishing_time"><span>出版时间:</span>2013-06-01</p> </div> </li> --> </ul> <div style="float:left; width: 100%; text-align: center;"> <hr/> <br/> <%@include file="/jsps/pager/pager.jsp" %> </div> </body> </html>
2)pager.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <script type="text/javascript"> function _go() { var pc = $("#pageCode").val();//获取文本框中的当前页码 if(!/^[1-9]\d*$/.test(pc)) {//对当前页码进行整数校验 alert('请输入正确的页码!'); return; } if(pc > ${pb.totalPages}) {//判断当前页码是否大于最大页 alert('请输入正确的页码!'); return; } location = "${pb.url}&pc=" + pc; } </script> <div class="divBody"> <div class="divContent"> <%--上一页 --%> <c:choose> <c:when test="${pb.currentPage eq 1 }"><span class="spanBtnDisabled">上一页</span></c:when> <c:otherwise> <a href="${pb.url }&pb=${pb.currentPage-1}" class="aBtn bold">上一页</a></c:otherwise> </c:choose> <%--我们需要计算页码列表的开始和结束位置,即两个变量begin和end,设定总共显示6页 计算它们需要通过当前页码! 1. 总页数不足6页--> begin=1, end=最大页 2. 总页数大于6页,通过公式设置begin和end,begin=当前页-2,end=当前页+3,因为假定总共显示6页 3. 如果begin<1,那么让begin=1,end=6 4. 如果end>tp, 让begin=tp-5, end=tp --%> <c:choose> <c:when test="${pb.totalPages <= 6 }"> <c:set var="begin" value="1"/> <c:set var="end" value="${pb.totalPages }"/> </c:when> <c:otherwise> <c:set var="begin" value="${pb.currentPage -2 }"/> <c:set var="end" value="${pb.currentPage + 3 }"/> <c:if test="${begin < 1 }"> <c:set var="begin" value="1"/> <c:set var="end" value="6"/> </c:if> <c:if test="${end > pb.totalPages }"> <c:set var="begin" value="${pb.totalPages - 5 }"/> <c:set var="end" value="${pb.totalPages }"/> </c:if> </c:otherwise> </c:choose> <%-- 显示页码列表 --%> <c:forEach begin="${begin }" end="${end }" var="i"> <c:choose> <c:when test="${i eq pb.currentPage }"><span class="spanBtnSelect">${i }</span></c:when> <c:otherwise><a href="${pb.url }&pc=${i}" class="aBtn">${i}</a></c:otherwise> </c:choose> </c:forEach> <%-- 显示点点点 --%> <c:if test="${end < pb.totalPages }"><span class="spanApostrophe">...</span> </c:if> <%--下一页 --%> <c:choose> <c:when test="${pb.currentPage eq pb.totalPages }"><span class="spanBtnDisabled">下一页</span></c:when> <c:otherwise><a href="${pb.url }&pc=${pb.currentPage+1}" class="aBtn bold">下一页</a> </c:otherwise> </c:choose> <%-- 共N页 到M页 --%> <span>共${pb.totalPages}页</span> <span>到</span> <input type="text" class="inputPageCode" id="pageCode" value="${pb.currentPage }"/> <span>页</span> <a href="javascript:_go();" class="aSubmit">确定</a> </div> </div>
2.servlet层
1)BookServlet.java
package com.tony.goods.book.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.servlet.BaseServlet; import com.tony.goods.book.domain.Book; import com.tony.goods.book.service.BookService; import com.tony.goods.pager.PageBean; public class BookServlet extends BaseServlet { private BookService bookService = new BookService(); /** * 按分类查 * @param req * @param resp * @return * @throws ServletException * @throws IOException */ public String findByCategory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1. 得到currentPage:如果页面传递,使用页面的,如果没传,currentPage=1 int currentPage = getCurrentPage(req); // 2. 得到url:... String url = getUrl(req); // 3. 获取查询条件,本方法就是cid,即分类的id String cid = req.getParameter("cid"); // 4. 使用currentPage和cid调用service#findByCategory得到PageBean PageBean<Book> pb = bookService.findByCategory(cid, currentPage); pb.setUrl(url); pb.setCurrentPage(currentPage); req.setAttribute("pb", pb); return "f:/jsps/book/list.jsp"; } /** * 截取url,页面中的分页导航中需要使用它做为超链接的目标! * @param req * @return */ /* * http://localhost:8080/goods/BookServlet?methed=findByCategory&cid=xxx&pc=3 * /goods/BookServlet + methed=findByCategory&cid=xxx&pc=3 */ private String getUrl(HttpServletRequest req) { String url = req.getRequestURI() + "?" + req.getQueryString(); // 如果url中存在pc参数,截取掉,如果不存在那就不用截取。 int index = url.lastIndexOf("&pc="); if(index != -1) url = url.substring(0, index); return url; } /** * 获取当前页码 * @param req * @return */ private int getCurrentPage(HttpServletRequest req) { int currentPage = 1; String param = req.getParameter("pc"); if(param != null && !param.trim().isEmpty()) { try { currentPage = Integer.parseInt(param); } catch (Exception e) { e.printStackTrace(); } } return currentPage; } }
3.service层
1)BookService.java
package com.tony.goods.book.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.servlet.BaseServlet; import com.tony.goods.book.domain.Book; import com.tony.goods.book.service.BookService; import com.tony.goods.pager.PageBean; public class BookServlet extends BaseServlet { private BookService bookService = new BookService(); /** * 按分类查 * @param req * @param resp * @return * @throws ServletException * @throws IOException */ public String findByCategory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1. 得到currentPage:如果页面传递,使用页面的,如果没传,currentPage=1 int currentPage = getCurrentPage(req); // 2. 得到url:... String url = getUrl(req); // 3. 获取查询条件,本方法就是cid,即分类的id String cid = req.getParameter("cid"); // 4. 使用currentPage和cid调用service#findByCategory得到PageBean PageBean<Book> pb = bookService.findByCategory(cid, currentPage); pb.setUrl(url); pb.setCurrentPage(currentPage); req.setAttribute("pb", pb); return "f:/jsps/book/list.jsp"; } /** * 截取url,页面中的分页导航中需要使用它做为超链接的目标! * @param req * @return */ /* * http://localhost:8080/goods/BookServlet?methed=findByCategory&cid=xxx&pc=3 * /goods/BookServlet + methed=findByCategory&cid=xxx&pc=3 */ private String getUrl(HttpServletRequest req) { String url = req.getRequestURI() + "?" + req.getQueryString(); // 如果url中存在pc参数,截取掉,如果不存在那就不用截取。 int index = url.lastIndexOf("&pc="); if(index != -1) url = url.substring(0, index); return url; } /** * 获取当前页码 * @param req * @return */ private int getCurrentPage(HttpServletRequest req) { int currentPage = 1; String param = req.getParameter("pc"); if(param != null && !param.trim().isEmpty()) { try { currentPage = Integer.parseInt(param); } catch (Exception e) { e.printStackTrace(); } } return currentPage; } }
4.dao层
1)BookDao.java
package com.tony.goods.book.dao; import java.sql.SQLException; 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 cn.itcast.jdbc.TxQueryRunner; import com.tony.goods.book.domain.Book; import com.tony.goods.pager.Expression; import com.tony.goods.pager.PageBean; import com.tony.goods.pager.PageConfig; public class BookDao { private QueryRunner qr = new TxQueryRunner(); /** * 删除图书 * @param bid * @throws SQLException */ public void delete(String bid) throws SQLException { String sql = "delete from t_book where bid=?"; qr.update(sql, bid); } /** * 按分类查询 * @param cid * @param currentPage * @return * @throws SQLException */ public PageBean<Book> findByCategory(String cid, int currentPage) throws SQLException { List<Expression> exprList = new ArrayList<Expression>(); exprList.add(new Expression("cid", "=", cid)); return findByCriteria(exprList, currentPage); } /** * 按书名模糊查询 * @param bname * @param currentPage * @return * @throws SQLException */ public PageBean<Book> findByBname(String bname, int currentPage) throws SQLException { List<Expression> exprList = new ArrayList<Expression>(); exprList.add(new Expression("bname", "like", "%" + bname + "%")); return findByCriteria(exprList, currentPage); } /** * 按作者查 * @param author * @param currentpage * @return * @throws SQLException */ public PageBean<Book> findByAuthor(String author, int currentpage) throws SQLException { List<Expression> exprList = new ArrayList<Expression>(); exprList.add(new Expression("author", "like", "%" + author + "%")); return findByCriteria(exprList, currentpage); } /** * 按出版社查 * @param press * @param currentpage * @return * @throws SQLException */ public PageBean<Book> findByPress(String press, int currentpage) throws SQLException { List<Expression> exprList = new ArrayList<Expression>(); exprList.add(new Expression("press", "like", "%" + press + "%")); return findByCriteria(exprList, currentpage); } /** * 多条件组合查询 * @param criteria * @param currentPage * @return * @throws SQLException */ public PageBean<Book> findByCombination(Book criteria, int currentPage) throws SQLException { List<Expression> exprList = new ArrayList<Expression>(); exprList.add(new Expression("bname", "like", "%" + criteria.getBname() + "%")); exprList.add(new Expression("author", "like", "%" + criteria.getAuthor() + "%")); exprList.add(new Expression("press", "like", "%" + criteria.getPress() + "%")); return findByCriteria(exprList, currentPage); } /** * 通用的查询方法 * @param exprList * @param currentPage * @return * @throws SQLException */ private PageBean<Book> findByCriteria(List<Expression> exprList, int currentPage) throws SQLException { /* * 1. 得到pageSize * 2. 得到totalRecords * 3. 得到beanList * 4. 创建PageBean,返回 */ /* * 1. 得到pageSize */ int pageSize = PageConfig.BOOK_PAGE_SIZE; /* * 2. 通过exprList来生成where子句 */ StringBuilder whereSql = new StringBuilder(" where 1=1"); List<Object> params = new ArrayList<Object>(); for(Expression expr : exprList) { /* * 添加一个条件上, * 1) 以and开头 * 2) 条件的名称 * 3) 条件的运算符,可以是=、!=、>、< ... is null,is null没有值 * 4) 如果条件不是is null,再追加问号,然后再向params中添加一与问号对应的值 */ whereSql.append(" and ").append(expr.getName()) .append(" ").append(expr.getOperator()).append(" "); // where 1=1 and bid = ? if(!expr.getOperator().equalsIgnoreCase("is null")) { whereSql.append("?"); params.add(expr.getValue()); } } /* * 3. 总记录数 */ String sql = "select count(*) from t_book" + whereSql; Number count = (Number) qr.query(sql, new ScalarHandler(), params.toArray()); int totalRecords = count.intValue();//得到了总记录数 /* * 4. 得到beanList,即当前页记录 */ sql = "select * from t_book" + whereSql + "order by orderBy limit ?,?"; params.add((currentPage - 1) * pageSize);//当前页首行记录的下标 params.add(pageSize);//每页记录数 List<Book> beanList = qr.query(sql, new BeanListHandler<Book>(Book.class), params.toArray()); /* * 5. 创建PageBean,设置参数 */ PageBean<Book> pb = new PageBean<Book>(); /* * 其中PageBean没有url,这个任务由Servlet完成 */ pb.setBeanList(beanList); pb.setCurrentPage(currentPage); pb.setPageSize(pageSize); pb.setTotalRecords(totalRecords); return pb; } }
相关文章推荐
- java中hashcode()和equals()的详解
- 基于分块统计和机器学习的主题类网页内容识别算法实现和应用范例
- WTL安装到VS2008和VS2010中
- Window7 64位环境下搭建redis开发环境(踩坑)
- Spring Tool Suite 设置必看,设置大全。
- 新的开始
- 基于分块统计和机器学习的主题类网页内容识别算法实现和应用范例
- html+css学习笔记:Sass语法学习
- [ExtJS5学习笔记]第三节 sencha cmd学习笔记 生成应用程序构建的内部细节
- Apache POI使用详解(excel为主)
- 性能测试的基本过程
- 在视频中实时地显示帧率
- Android Binder进程间通信深入分析
- 初识WTL
- UML类图五种关系与代码的对应关系
- 2-Linux-虚拟机系统安装
- HDOJ 1251 统计难题(字典树)
- 检测一个数组缺少哪几个数
- 安装使用Oracle OSWbb/OSWbba工具
- 在Ext JS 6中添加本地化包