10.按类别查询分页
提交方式:
<a href="${pageContext.request.contextPath}/product?method=findByPage2&category=文学">文学</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=生活">生活</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=计算机">计算机</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=外语">外语</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=经营">经管</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=励志">励志</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=社科">社科</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=学术">学术</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=少儿">少儿</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=艺术">艺术</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=原版">原版</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=科技">科技</a> <a href="${pageContext.request.contextPath}/product?method=findByPage2&category=考试">考试</a>
三层架构:
ProductServlet /** * 根据类别查询并分页 * @param request * @param response * @throws ServletException * @throws IOException */ public void findByPage2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取分类 String category=request.getParameter("category"); System.out.println(category); //一般情况下,服务器默认的编码是“iso8859-1”,所以我们需要数据还原,然后再转换成UTF-8的形式 //如果要调用request.setCharacterEncoding进行编码设置,一定要在任何参数被访问之前调用。 //if(category!=null){ // category=new String(category.getBytes("iso8859-1"),"utf-8"); //} //获取页码 int pageCode=getPageCode(request); //每页显示的记录条数 int pageSize=4; //调用业务层 ProductService ps=new ProductService(); //分类分页的查询 PageBean page=ps.findByPage(pageCode,pageSize,category);
//获取连接,设置到page的对象中
page.setUrl(getUrl(request));
request.setAttribute("page", page); request.getRequestDispatcher("/product_list.jsp").forward(request, response); } ProductService /** * 根据类别查询并分页 * @param pageCode * @param pageSize * @param category * @return */ public PageBean findByPage(int pageCode, int pageSize, String category) { ProductDao dao=new ProductDao(); return dao.findByPage(pageCode,pageSize,category); } ProductDao /** * 根据类别查询并分页 * @param pageCode * @param pageSize * @param category * @return */ public PageBean findByPage(int pageCode, int pageSize, String category) { //存储cansh List<Object> list=new ArrayList(); PageBean<Product> page=new PageBean<Product>(); page.setPageCode(pageCode); page.setPageSize(pageSize); QueryRunner runner=new QueryRunner(MyJdbcUtils.getDataSource()); String countSql=null; String selSql=null; if(category!=null){ countSql="select count(*) from products where category=?"; selSql="select * from products where category=? limit ?,?"; list.add(category); }else{ countSql="select count(*) from products "; selSql="select * from products limit ?,?"; } try { //查询总记录的条数 long totalCount=(long) runner.query(countSql, new ScalarHandler(),list.toArray()); //设置条数 page.setTotalCount((int)totalCount); list.add((pageCode-1)*pageSize); list.add(pageSize); //查询每页显示的条数 List<Product> beanList=runner.query(selSql, new BeanListHandler<Product>(Product.class),list.toArray()); page.setBeanList(beanList); } catch (SQLException e) { e.printStackTrace(); } return page; }
javabean:
/** * 分页的javabean * @author mjl * */ public class PageBean<T> { //当前页 private int pageCode; //总页数=总记录数/每页 显示的条数 //private int totalPage; //总记录数 private int totalCount; //每页显示的条数 private int pageSize; //每页显示的数据 private List<T> beanList; //新添加一个属性,作为分页的条件出现的 private String url; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getPageCode() { return pageCode; } public void setPageCode(int pageCode) { this.pageCode = pageCode; } public int getTotalPage() { int totalPage=totalCount/pageSize; if(totalCount % pageSize ==0){ return totalPage; }else{ return totalPage+1; } } /* //不用自己设置值的,这是计算出来的 public void setTotalPage(int totalPage) { this.totalPage = totalPage; }*/ //获取总页数 public int getTotalCount() { //可以计算 return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public List<T> getBeanList() { return beanList; } public void setBeanList(List<T> beanList) { this.beanList = beanList; } }
product_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>bookStore列表</title> <%--导入css --%> <link rel="stylesheet" href="css/main.css" type="text/css" /> </head> <body class="main"> <jsp:include page="head.jsp" /> <jsp:include page="menu_search.jsp" /> <div id="divpagecontent"> <table width="100%" border="0" cellspacing="0"> <tr> <td> <div style="text-align:right; margin:5px 10px 5px 0px"> <a href="index.jsp">首页</a> > 计算机 > 图书列表 </div> <table cellspacing="0" class="listcontent"> <tr> <td> <h1>商品目录</h1> <hr /> <h1>计算机</h1> 共${page.totalCount }种商品 <hr /> <div style="margin-top:20px; margin-bottom:5px"> <img src="images/productlist.gif" width="100%" height="38" /> </div> <table cellspacing="0" class="booklist"> <!-- 一页只有四个 对象,所以遍历4次 --> <tr> <c:forEach var="p" items="${page.beanList }"> <td> <div class="divbookpic"> <p> <a href="${pageContext.request.contextPath }/product?method=findInfo&pid=${p.pid}"> <img src="bookcover/101.jpg" width="115" height="129" border="0" /> </a> </p> </div> <div class="divlisttitle"> <a href="${pageContext.request.contextPath }/product?method=findInfo&pid=${p.pid}"> 书名:${p.pname }<br />售价:${p.price } </a> </div> </td> </c:forEach> </tr> </table> <div class="pagination"> <ul> <c:if test="${page.pageCode>1 }"> <li class="disablepage"> <a href="${page.url }&pc=${page.pageCode-1}">上一页</a> <%-- <a href="${pageContext.request.contextPath }/product?method=findByPage&pc=${page.pageCode-1}" >上一页</a> --%> </li> </c:if> <!--也可以产生这种循环 for(int i=1;i<=10;i++){} --> <%-- 目的:控制begin和end的值 逻辑: 当总页数<=10,说明一共不超过10页,让begin=1,end=总页数 当总页数>10,让begin=pageCode-5,end=pageCode+4 头溢出: 如果当前页=3,begin=3-5=-2 如果begin<1,让begin=1,end=10 尾溢出: 如果end>总页数,让end=总页数,begin=总页数-9 --%> <!-- 编写逻辑 判断开始页码结束页码--> <c:choose> <c:when test="${page.totalPage<=10 }"> <c:set var="begin" value="1" ></c:set> <c:set var="end" value="${page.totalPage }"></c:set> </c:when> <c:otherwise> <c:set var="begin" value="${page.pageCode-5 }" ></c:set> <c:set var="end" value="${page.pageCode+4 }"></c:set> <!-- 判断头溢出 --> <c:if test="${begin<1 }"> <c:set var="begin" value="1" ></c:set> <c:set var="end" value="10"></c:set> </c:if> <!-- 判断尾溢出 --> <c:if test="${end>page.totalPage }"> <c:set var="begin" value="${page.totalPage-9 }" ></c:set> <c:set var="end" value="${page.totalPage }"></c:set> </c:if> </c:otherwise> </c:choose> <c:forEach var="i" begin="${begin }" end="${end }" step="1"> <!-- 当前页==i --> <c:if test="${page.pageCode==i }"> <li class="currentpage">${i }</li> </c:if> <c:if test="${page.pageCode!=i }"> <li> <%-- <a href="${pageContext.request.contextPath }/product?method=findByPage&pc=${i}">${i }</a> --%> <a href="${page.url }&pc=${i}">${i }</a> </li> </c:if> </c:forEach> <c:if test="${page.pageCode<page.totalPage }"> <li class="nextpage"> <a href="${page.url }&pc=${page.pageCode+1}">下一页</a> <%-- <a href="${pageContext.request.contextPath }/product?method=findByPage&pc=${page.pageCode+1}">下一页</a> --%> </li> </c:if> </ul> </div> </td> </tr> </table> </td> </tr> </table> </div> <jsp:include page="foot.jsp" /> </body> </html>
获取图书详细信息:
ProductServlet:
/** * 查询书的详细的信息 * @param request * @param response * @throws ServletException * @throws IOException */ public void findInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收Id String pid=request.getParameter("pid"); // ProductService ps=new ProductService(); Product p=ps.findById(pid); request.setAttribute("p", p); request.getRequestDispatcher("/product_info.jsp").forward(request, response); }
product_info:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>电子书城</title> <link rel="stylesheet" href="css/main.css" type="text/css" /> </head> <body class="main"> <jsp:include page="head.jsp" /> <jsp:include page="menu_search.jsp" /> <div id="divpagecontent"> <table width="100%" border="0" cellspacing="0"> <tr> <td><div style="text-align:right; margin:5px 10px 5px 0px"> <a href="index.html">首页</a> > <a href="product_list.html"> ${p.category }</a> > ${p.pname } </div> <table cellspacing="0" class="infocontent"> <tr> <td><img src="ad/page_ad.jpg" width="645" height="84" /> <table width="100%%" border="0" cellspacing="0"> <tr> <td width="30%"> <div class="divbookcover"> <p> <img src="bookcover/101.jpg" width="213" height="269" border="0" /> </p> </div> <div style="text-align:center; margin-top:25px"> <!-- 点击购买 --> <a href="${pageContext.request.contextPath }/cart?method=addToCart&pid=${p.pid}"> <img src="images/buybutton.gif" border="0" /> </a> </div> </td> <td style="padding:20px 5px 5px 5px"> <img src="images/miniicon3.gif" width="16" height="13" /> <font class="bookname"> ${p.pname }</font> <hr />售价:<font color="#FF0000">${p.price }</font> <hr /> 类别:${p.category } <hr /> <p> <b>内容简介:</b> </p> ${p.description } </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </div> <jsp:include page="foot.jsp" /> </body> </html>
点击购买,跳转到购物车
JavaBean:
购物项:
/** * 购物项 * 包含 购买的数量 小计 商品 * @author mjl * */ public class CartItem { //编写属性 //商品 private Product product; //购买的数量 private int buyNum; //小计 private double subtotal; public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public int getBuyNum() { return buyNum; } public void setBuyNum(int buyNum) { this.buyNum = buyNum; } //小计是算出来的,干掉set,留get public double getSubtotal() { return product.getPrice()*buyNum; } /*public void setSubtotal(double subtotal) { this.subtotal = subtotal; }*/ }
购物车:
/** * 购物车 * 购物车包含:多个购物项 合计 * @author mjl * */ public class Cart { //合计=小计的和 private double total; //包含多个购物项(list删除需要遍历,map.remove(key),所以map更容易操作) private Map<String,CartItem> map=new HashMap(); // public double getTotal() { double t=0; //获取map集合中所有的购物项 for(String key:map.keySet()){ CartItem item=map.get(key); //获取购物项的小计 t+=item.getSubtotal(); } return t; } public void setTotal(double total) { this.total = total; } public Map<String, CartItem> getMap() { return map; } public void setMap(Map<String, CartItem> map) { this.map = map; } //提供方法:把购买的购物项保存到map集合中 public void addCart(CartItem item){ //把购物项存入到购物车中,(其实就是向map集合中存入) //map.put(item.getProduct().getPid(), item); /** * 如果购买的是相同的书,数量+1 * 如果购买的不同的书,直接存入到map集合中 */ //获取商品的主键 String pid=item.getProduct().getPid(); //判断,map集合中是否包含该主键 if(map.containsKey(pid)){ //之前存入过一次了,直接更新数量就可以了 CartItem hisItem=map.get(pid); hisItem.setBuyNum(hisItem.getBuyNum()+item.getBuyNum()); }else{ //说明第一次存入该商品 map.put(pid, item); } } }
CartServlt:
public class CartServlet extends BaseServlet { /** * 把购买的商品添加到购物车中 * @param request * @param response * @throws ServletException * @throws IOException */ public void addToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 1.先得准备商品 * 2.准备购物项 * 3.把购物项添加到购物车中 */ //1.先得准备商品 String pid=request.getParameter("pid"); //查询 ProductService ps=new ProductService(); Product product=ps.findById(pid); //2.准备购物项 CartItem item=new CartItem(); item.setProduct(product); item.setBuyNum(1); //3.把购物项添加到购物车中,购物车存到session中 //Cart cart=new Cart(); Cart cart=getCart(request); cart.addCart(item); //跳转到购物车的页面,显示数据 //session是会话级别,多次请求响应,用重定向 response.sendRedirect(request.getContextPath()+"/cart.jsp"); } /** * 获取购物车 * @param request * @return */ public Cart getCart(HttpServletRequest request){ /** * 如果是第一次访问,没有购物车,创建购物车,存入到session中 * 如果不是第一次访问,直接从session中获取购物车 */ HttpSession session=request.getSession(); //获取购物车 Cart cart=(Cart) session.getAttribute("cart"); //如果是第一次,cart=null if(cart==null){ //创建购物车 cart=new Cart(); //非常重要,存购物车 session.setAttribute("cart", cart); } return cart; } }
点击x号,删除商品。点击+ -号,增加减少商品
cart.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> <link rel="stylesheet" href="css/main.css" type="text/css" /> <script type="text/javascript"> //点击+号,添加购买数量 function addCount(pid,count){ window.location.href="${pageContext.request.contextPath}/cart?method=addCount&pid="+pid+"&count="+count; } //点击-号,减少购买数量 function removeCount(pid,count){ window.location.href="${pageContext.request.contextPath}/cart?method=removeCount&pid="+pid+"&count="+count; } </script> </head> <body class="main"> <jsp:include page="head.jsp" /> <jsp:include page="menu_search.jsp" /> <div id="divpagecontent"> <table width="100%" border="0" cellspacing="0"> <tr> <td><div style="text-align:right; margin:5px 10px 5px 0px"> <a href="index.html">首页</a> > 购物车 </div> <table cellspacing="0" class="infocontent"> <tr> <td><img src="ad/page_ad.jpg" width="666" height="89" /> <table width="100%" border="0" cellspacing="0"> <tr> <td><img src="images/buy1.gif" width="635" height="38" /> </td> </tr> <tr> <td> <table cellspacing="1" class="carttable"> <tr> <td width="10%">序号</td> <td width="30%">商品名称</td> <td width="10%">价格</td> <td width="20%"> 数量</td> <td width="10%">库存</td> <td width="10%">小计</td> <td width="10%">取消</td> </tr> </table> <!-- for(Entry entry:map){} Map<String, CartItem>--> <c:forEach var="entry" items="${cart.map }" varStatus="vs"> <table width="100%" border="0" cellspacing="0"> <tr> <td width="10%">${vs.count }</td> <td width="30%">${entry.value.product.pname }</td> <td width="10%">${entry.value.product.price}</td> <td width="20%"> <!-- 加减号更新数量 --> <input type="button" value='-' style="width:20px" onclick="removeCount('${entry.value.product.pid}','${entry.value.buyNum-1 }');"> <!-- 中间显示的数量 --> <input name="text" type="text" value="${entry.value.buyNum }" style="width:40px;text-align:center" /> <input type="button" value='+' style="width:20px" onclick="addCount('${entry.value.product.pid}','${entry.value.buyNum+1 }');"> </td> <td width="10%">${entry.value.product.pnum }</td> <td width="10%">${entry.value.subtotal}</td> <td width="10%"> <a href="${pageContext.request.contextPath }/cart?method=removeCart&pid=${entry.value.product.pid}" style="color:#FF0000; font-weight:bold">X</a> </td> </tr> </table> </c:forEach> <table cellspacing="1" class="carttable"> <tr> <td style="text-align:right; padding-right:40px;"><font style="color:#FF6600; font-weight:bold">合计: ${cart.total }</font> </td> </tr> </table> <div style="text-align:right; margin-top:10px"> <a href="${ pageContext.request.contextPath }/product?method=findByPage2"> <!-- 继续购物 --> <img src="images/gwc_jx.gif" border="0" /> </a> <a href="order.jsp"> <!-- 结账 --> <img src="images/gwc_buy.gif" border="0" /> </a> </div> </td> </tr> </table> </td> </tr> </table></td> </tr> </table> </div> <jsp:include page="foot.jsp" /> </body> </html>
CartServlet:
/** * 点击X号,删除某一个购物项 * @param request * @param response * @throws ServletException * @throws IOException */ public void removeCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 获取商品的id * 从session中获取购物车 * 从购物车中再获取map集合 * 通过id删除购物项 * 重新跳回到购物车的页面 */ String pid=request.getParameter("pid"); HttpSession session=request.getSession(); Cart cart=(Cart) session.getAttribute("cart"); cart.getMap().remove(pid); response.sendRedirect(request.getContextPath()+"/cart.jsp"); } /** * 点击+号,增加商品的数量 * @param request * @param response * @throws ServletException * @throws IOException */ public void addCount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pid=request.getParameter("pid"); String sCount=request.getParameter("count"); int count=Integer.parseInt(sCount); //判断 //获取购物车 HttpSession session=request.getSession(); Cart cart=(Cart) session.getAttribute("cart"); //获取购物车中的map集合,通过商品的主键获取到具体购物项 Map<String,CartItem> map=cart.getMap(); CartItem item=map.get(pid); //判断,购买数量不能大于库存 if(count>item.getProduct().getPnum()){ //跳回购物车页面 response.sendRedirect(request.getContextPath()+"/cart.jsp"); return; } //更新数量 item.setBuyNum(count); //跳回购物车页面 response.sendRedirect(request.getContextPath()+"/cart.jsp"); } /** * 点击-号,减少商品的数量 * @param request * @param response * @throws ServletException * @throws IOException */ public void removeCount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pid=request.getParameter("pid"); String sCount=request.getParameter("count"); int count=Integer.parseInt(sCount); HttpSession session=request.getSession(); Cart cart=(Cart) session.getAttribute("cart"); Map<String,CartItem> map=cart.getMap(); CartItem item=map.get(pid); if(count<1){ response.sendRedirect(request.getContextPath()+"/cart.jsp"); return; } item.setBuyNum(count); response.sendRedirect(request.getContextPath()+"/cart.jsp"); }