图书购买系统之商品分类分页--根据主页面传来的值分类显示商品并实现动态分页功能

来源:互联网 发布:清朗网络海报 编辑:程序博客网 时间:2024/05/17 23:56

1.实现效果图


2.home.jsp,主页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta charset="utf-8" /><title>bootstore</title><!--引入bootstrap.css--><link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/bootstrap/css/bootstrap.css"/><!--引入myscss.css--><link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/myscss.css" /><!--引入jquery.js--><script type="text/javascript" src="<%=request.getContextPath()%>/bootstrap/js/jquery-3.1.1.js"></script><!--bootstrap.js--><script type="text/javascript" src="<%=request.getContextPath()%>/bootstrap/js/bootstrap.js"></script><!--home.js--><script type="text/javascript" src="<%=request.getContextPath()%>/foreground/book/home.js"></script><!--contextPath--><script type="text/javascript">var contextPath = "${pageContext.request.contextPath}";</script></head><body><!--公用头部--><!-- <div id="navhead"></div> --><%@include file="/foreground/common/head.jsp"%><!--<nav class="navbar navbar-default">  <div class="container">    <div class="navbar-header">      <button type="button" data-toggle="collapse" data-target="#collapse-1" aria-expanded="false" class="navbar-toggle collapsed">        <span class="sr-only">Toggle navigation</span>        <span class="icon-bar"></span>        <span class="icon-bar"></span>        <span class="icon-bar"></span>        <span class="icon-bar"></span>      </button>      <a href="index.html">      <img src="../../img/bookimages/logo.png" />      </a>    </div>    <div class="collapse navbar-collapse backcolor" id="collapse-1">      <ul class="nav navbar-nav pull-right">      <li><a href="#"><span class="glyphicon glyphicon-shopping-cart">购物车|</span></a></li>      <li><a href="#"><span class="glyphicon glyphicon-question-sign">帮助中心|</span></a></li>      <li><a href="login.html"><span class="glyphicon glyphicon-user">我的账户|</span></a></li>      <li><a href="register.html"><span class="glyphicon glyphicon-pencil">新用户注册</span></a></li>      </ul>    </div>  </div></nav>--><!--导航栏--><div class="container"><div class="text-nowrap text-center menu"><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=文学">文学</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=生活">生活</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=计算机">计算机</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=外语">外语</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=经管">经管</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=励志">励志</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=社科">社科</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=学术">学术</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=少儿">少儿</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=艺术">艺术</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=原版">原版</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=科技">科技</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=考试">考试</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=生活百科">生活百科</a><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=全部目录商品" id="yellow">全部目录商品</a></div><div class="clearfix searchcolor"><form class="navbar-form navbar-right searchmargin" role="search"><div class="form-group">    <input id="searchContent" type="text" class="form-control">    <div id="searchResult" style="background:Snow;position:absolute;left:71%;width:15%;z-index:1;"></div></div><button type="button" onclick="doSearch()" class="btn btn-info">搜索</button></form></div></div><!--新书上架--><div class="container margintop"><div class="row"><div class="col-md-2"></div><div class="col-md-8"><div class="media">  <div class="media-left">    <a href="#">      <img class="media-object" src="<%=request.getContextPath()%>/img/otherimages/home_book.PNG" alt="图书">    </a>  </div>  <div class="media-right paddingleft">    <h2 class="bg-danger">新书上架</h2>    <h5 class="htext">JAVA入门经典</h5>    <p class="text-muted">《Java入门经典》,是2012年出版的图书,是2012年出版的图书是2012年出版的图书作者是Rogers Cadenhead。 《Java入门经典(第6版)》总共24章,先讲解了Java程序的编写流程、工作原理等内容;然后介绍了有关Java编程 的基本知识,包括变量、条件语句、</p>  <img class="img-responsive thumbnail" src="<%=request.getContextPath()%>/img/otherimages/home_book2.PNG">  </div></div></div><div class="col-md-2"></div></div></div><!--公告板和本周热卖--><div class="container margintop"><div class="row"><div class="col-md-1"></div><div class="col-md-5"><h2 class="bg-success">公告板</h2><ul class="list-group-item"><li><a>图书三折起</a></li><li><a>甩卖了,<java疯狂讲义10元起售></a></li><li><a>新书到了,欢迎订购</a></li><li><a>系统维护通知</a></li><li><a>好消息好消息</a></li></ul></div><div class="col-md-5"><h2 class="bg-danger">本周热卖</h2><div class="pull-left text-center" id="book"><div class="col-sm-6"><img src="<%=request.getContextPath()%>/img/bookimage/20285763-1_b.jpg" /><br /><span>书名:java核心技术</span><br /><span>售价:XXX</span></div><div class="col-sm-6"><img src="<%=request.getContextPath()%>/img/bookimage/20412979-1_b.jpg" /><br /><span>书名:javascript</span><br /><span>售价:XXX</span></div></div></div><div class="col-md-1"></div></div></div><nav class="navbar navbar-default bottom margin"><div class="container"><div class="row"><div class="col-md-1"></div><div class="col-md-4"><img src="<%=request.getContextPath()%>/img/otherimages/logo.png"></div><div class="col-md-7"><div style="margin-top: 10px;">CONTACT US<br>    COPYRIGHT 2017 ©BootStore AS Rights RESERVED</div></div></div></div></nav></body></html>

3.home.js

//输入框键盘弹起事件,在这里发送ajax请求$(function(){$("#searchContent").keyup(function(){//设置ajax请求url和请求内容var sendUrl = contextPath+"/AjaxShowSearchProductNameServlet?time"+new Date().getTime();var sendDate = {"value":$("#searchContent").val()}//发送ajax请求$.ajax({type:"post",url:sendUrl,data:sendDate,async:true,//请求成功的回调函数success:function(backData,textStatus,xmlHttprequest){var ss = backData.split(",");var childDiv = "";for(var i = 0;i < ss.length;i++){childDiv +="<div onclick='setSearchContent(this)'>" + ss[i] + "</div>";}//显示搜索框$("#searchResult").html(childDiv);$("#searchResult").show();}});});});//选中搜索列表中的一条数据,设置为搜索框内容function setSearchContent(caller){$("#searchContent").val($(caller).html());$("#searchResult").hide();}//搜索功能function doSearch(){//获取要搜索的内容var category = $("#searchContent").val();//alert(contextPath+"/ShowBlurProductsServlet?category="+category);window.location.href = contextPath+"/ShowBlurProductsServlet?category="+category;}


4.bookcategory.jsp,分页页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE html><html><head><meta charset="UTF-8"><title>bookcategory</title><!--引入bootstrap.css--><link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/bootstrap/css/bootstrap.css"/><!--引入myscss.css--><link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/myscss.css" /><!--引入jquery.js--><script type="text/javascript" src="<%=request.getContextPath()%>/bootstrap/js/jquery-3.1.1.js"></script><!--bootstrap.js--><script type="text/javascript" src="<%=request.getContextPath()%>/bootstrap/js/bootstrap.js"></script><!--bookcategory.js--><script type="text/javascript" src="<%=request.getContextPath()%>/foreground/book/bookcategory.js"></script></head><body><!--公用头部--><!-- <div id="navhead"></div> --><%@include file="/foreground/common/head.jsp"%><!--路径导航--><div class="container"><ol class="breadcrumb">  <li><a href="<%=request.getContextPath()%>/foreground/book/home.jsp">首页</a></li>  <li><a id="navpath" href="#">全部商品</a></li></ol></div><!--商品列表--><div class="container"><div class="row"><div class="col-md-1"></div><div class="col-md-10"><img class="img" src="<%=request.getContextPath()%>/img/otherimages/productlist.gif" /><div class="text-center" id="books"><c:forEach var="book" varStatus="bookidx" items="${bookPage.ps}"><div class="col-md-3"><div class="thumbnail"><img src="<%=request.getContextPath()%>/${book.imgurl}"/><br /><span>书名:${book.name}</span><br /><span>售价:${book.price}</span><br /><input type="image" onclick="addCart('${book.id}','${book.name}','${book.price}','${book.num}')" src="<%=request.getContextPath()%>/img/bookimages/buybutton.gif" /></div></div></c:forEach></div></div><div class="col-md-1"></div></div></div><!--分页--><c:if test="${bookPage.isblur!='yes'}"><div class="container">  <nav class="text-center">  <ul class="pagination text-center" >    <li><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=1&category=${bookPage.category}"><span>«首页</span> </a></li>    <li><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=${(bookPage.currentPage>1)?(bookPage.currentPage-1):1}&category=${bookPage.category}">上一页</a></li>    <li><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=${(bookPage.currentPage<bookPage.totalPage)?(bookPage.currentPage+1):bookPage.totalPage}&category=${bookPage.category}">下一页</a></li>    <li><a href="<%=request.getContextPath()%>/ShowProductsServlet?currentPage=${bookPage.totalPage}&category=${bookPage.category}"> <span>末页»</span></a></li>    <li class="pagespan">${bookPage.currentPage}/${bookPage.totalPage}</li>  </ul></nav></div></c:if></body></html>


5.bookcategory.js

//1.路径导航部分//截取从home.html传过来的URL$(function(){var url = window.location.search;//从问号 (?) 开始的 URL(查询部分),此时等号后面是乱码url = decodeURI(url);//解码,把乱码变成正常的文字var substr = url.substr(url.indexOf("category=")+9);//截取字符串,截取category=之后的内容$("#navpath").html(substr);//将截取到的字符串放到路径导航的位置});//2.添加购物车部分//思路:把添加购物车的数据存放在localStorage中//方法传参:书的id,书名,书售价,书的库存function addCart(id,name,price,num){//1.创建一个js对象var book = {"product_id":id,   //书的id"name":name,       //书名"price":price,     //售价"num":num,         //库存"buynum":1         //购买数量}//2.获取已经保存的数据var storebook = localStorage.getItem("carts");//3.将已经获取到的数据转换成数组var bookArr = JSON.parse(storebook);//JSON.parse() 方法解析一个JSON字符串//如果购物车离得数据为空,说明从来没有保存过数据if(bookArr == null){//创建一个数组var books = new Array();//把要保存的数据存到数组中books.push(book);//将数组转换成字符串var bookstr = JSON.stringify(books);//将字符串保存到localStorge中localStorage.setItem("carts",bookstr);}//已经存过数据了else{//1.判断我们存的书籍是否已经在购物车了,如果存在,数量+1var isFind = false;for(var i = 0;i < bookArr.length; i++){var b = bookArr[i];if(b.product_id == book.product_id){b.buynum++;isFind = true;break;}}//2.如果不存在,将书籍添加到购物车中if(isFind == false){bookArr.push(book);}//3.把bookArr重新转换成字符串保存var s = JSON.stringify(bookArr);localStorage.setItem("carts",s);}alert("添加成功!");}


6.ShowProductsServlet.java,处理书籍信息显示

package com.chinasoft.servlet;import java.io.IOException;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.chinasoft.dao.impl.ImplProductDao;import com.chinasoft.entity.PageBean;/** * @author jf * 处理书籍信息的显示 */@WebServlet("/ShowProductsServlet")public class ShowProductsServlet extends HttpServlet {private static final long serialVersionUID = 1L;           public ShowProductsServlet() {        super();    }protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取请求参数String currentPage = request.getParameter("currentPage");String category = request.getParameter("category");//2.根据请求参数查询数据库ImplProductDao implProductDao = new ImplProductDao();try {PageBean bookPage = implProductDao.findPageBooks(Integer.parseInt(currentPage), 8, category);//3.保存数据、跳转页面request.getSession().setAttribute("bookPage", bookPage);request.getRequestDispatcher("/foreground/book/bookcategory.jsp").forward(request, response);} catch (NumberFormatException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}

7.AjaxShowSearchProductNameServlet.java实现模糊查询书名

package com.chinasoft.servlet;import java.io.IOException;import java.sql.SQLException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.chinasoft.dao.impl.ImplProductDao;import com.chinasoft.entity.Product;/** * @author jf * 功能:根据搜索条件返回符合条件的书名 */@WebServlet("/AjaxShowSearchProductNameServlet")public class AjaxShowSearchProductNameServlet extends HttpServlet {private static final long serialVersionUID = 1L;           public AjaxShowSearchProductNameServlet() {        super();    }protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取请求参数String value = request.getParameter("value");ImplProductDao implProductDao = new ImplProductDao();try {//2.根据请求模糊检索数据库List<Product> list = implProductDao.findBooksByBlurName(value);//3.把所有符合条件的书拼接成字符串String books = "";if("".equals(value)){}else{for(int i = 0;i<list.size();i++){if(i>0){books += ",";}books += list.get(i).getName();}}//4.向客户端输出字符串response.getWriter().write(books);} catch (SQLException e) {e.printStackTrace();}}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}


8.ShowBlurProductsServlet.java根据搜索框的搜索内容,搜索符合条件的书籍,跳转新页面显示书籍

package com.chinasoft.servlet;import java.io.IOException;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.chinasoft.dao.impl.ImplProductDao;import com.chinasoft.entity.PageBean;/** * @author jf * 根据搜索框的搜索内容,搜索符合条件的书籍,跳转新页面显示书籍 */@WebServlet("/ShowBlurProductsServlet")public class ShowBlurProductsServlet extends HttpServlet {private static final long serialVersionUID = 1L;           public ShowBlurProductsServlet() {        super();    }protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取请求参数String category = request.getParameter("category");//2.根据请求参数查询数据库ImplProductDao implProductDao = new ImplProductDao();try {PageBean bookPage = implProductDao.findPageBooksByBlurName(category);//3.保存数据、跳转页面request.getSession().setAttribute("bookPage", bookPage);request.getRequestDispatcher("/foreground/book/bookcategory.jsp").forward(request, response);}catch (NumberFormatException e) {e.printStackTrace();}catch (SQLException e) {e.printStackTrace();}}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}

9.ShowProductsServlet.java处理书籍信息的显示

package com.chinasoft.servlet;import java.io.IOException;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.chinasoft.dao.impl.ImplProductDao;import com.chinasoft.entity.PageBean;/** * @author jf * 处理书籍信息的显示 */@WebServlet("/ShowProductsServlet")public class ShowProductsServlet extends HttpServlet {private static final long serialVersionUID = 1L;           public ShowProductsServlet() {        super();    }protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取请求参数String currentPage = request.getParameter("currentPage");String category = request.getParameter("category");//2.根据请求参数查询数据库ImplProductDao implProductDao = new ImplProductDao();try {PageBean bookPage = implProductDao.findPageBooks(Integer.parseInt(currentPage), 8, category);//3.保存数据、跳转页面request.getSession().setAttribute("bookPage", bookPage);request.getRequestDispatcher("/foreground/book/bookcategory.jsp").forward(request, response);} catch (NumberFormatException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}

10.ProductDao.java接口

package com.chinasoft.dao;import java.sql.SQLException;import java.util.List;import com.chinasoft.entity.PageBean;import com.chinasoft.entity.Product;public interface ProductDao {//查找所有的书籍public List<Product> findAllBooks() throws SQLException;//根据书的id查找指定的书籍public Product findBookById(String id) throws SQLException;//查找某一分类下的书籍总数public long count(String category) throws SQLException;//分页查询,查找当前页下、每页显示指定size下、以及当前分类下的书籍public List<Product> findBooks(int currentPage, int pageSize,String category) throws SQLException;//根据指定书名搜索书籍public Product searchBookByName(String name) throws SQLException;//模糊检索,根据模糊条件查找数据库,返回list集合public List<Product> findBooksByBlurName(String name) throws SQLException;//模糊检索,根据模糊条件查找数据库,返回pageBeanpublic PageBean findPageBooksByBlurName(String name) throws SQLException;//分页查询,返回pageBean,pegeBean封装了当前页的所有信息public PageBean findPageBooks(int currentPage, int pageSize,String category) throws SQLException;}

11.ImplProductDao.java,ProductDao接口实现类

package com.chinasoft.dao.impl;import java.sql.SQLException;import java.util.List;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import org.apache.commons.dbutils.handlers.BeanListHandler;import org.apache.commons.dbutils.handlers.ScalarHandler;import com.chinasoft.dao.ProductDao;import com.chinasoft.entity.PageBean;import com.chinasoft.entity.Product;import com.chinasoft.util.C3P0Util;public class ImplProductDao implements ProductDao{/** * 查找所有的书籍 */@Overridepublic List<Product> findAllBooks() throws SQLException {//1.创建QueryRunner对象QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());List<Product> list = qr.query("select * from products", new BeanListHandler<>(Product.class));return list;}/** * 根据书的id查找指定的书籍 */@Overridepublic Product findBookById(String id) throws SQLException {QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());String sql = "select * from products where id=?";Product product = qr.query(sql,new BeanHandler<Product>(Product.class),id);return product;}/** * 查找某一分类下的书籍总数 */@Overridepublic long count(String category) throws SQLException {QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());String sql = null;long count = 0;if ("全部商品目录".equals(category)) {sql = "select COUNT(*) from products";count = qr.query(sql, new ScalarHandler<>());}else{sql = "select COUNT(*) from products where category=?";count = qr.query(sql, new ScalarHandler<>(),category);}return count;}/** * * 分页查询,查找当前页下、每页显示指定size下、以及当前分类下的所有书籍 */@Overridepublic List<Product> findBooks(int currentPage, int pageSize, String category) throws SQLException {QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());String sql = null;List<Product> products = null;if ("全部商品目录".equals(category)) {sql = "select * from products limit ?,?";if (currentPage>=1) {products = qr.query(sql, new BeanListHandler<>(Product.class),(currentPage-1)*pageSize,pageSize);}}else{sql = "select * from products where category=? limit ?,?";if (currentPage>=1) {products = qr.query(sql, new BeanListHandler<>(Product.class), category,(currentPage-1)*pageSize,pageSize);}}return products;}/** * 根据指定书名搜索书籍 */@Overridepublic Product searchBookByName(String name) throws SQLException {QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());String sql = "select * from products where name=?";Product product = qr.query(sql,new BeanHandler<Product>(Product.class),name);return product;}/** * 模糊检索,根据模糊条件查找数据库,返回list */@Overridepublic List<Product> findBooksByBlurName(String name) throws SQLException {//1.创建QueryRunner对象QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());List<Product> list = qr.query("select * from products where name like ?", new BeanListHandler<>(Product.class),"%"+name+"%");return list;}/** * 模糊检索,根据模糊条件查找数据库,返回pagebean */@SuppressWarnings("unused")@Overridepublic PageBean findPageBooksByBlurName(String name) throws SQLException {// 1.获取符合条件的书的集合List<Product> list = findBooksByBlurName(name);// 2.获取搜索到的所有书籍的个数int totalcount = list.size();// 3.设置当前页和最大页int currentPage = 1;int totalPage = 1;if (totalcount == 0) {currentPage = 0;totalPage = 0;}// 4.创建PageBean对象PageBean pageBean = new PageBean();pageBean.setCurrentPage(currentPage);pageBean.setTotalCount(totalcount);pageBean.setTotalPage(totalcount);pageBean.setCurrentCount(totalcount);pageBean.setIsblur("yes");if (list!=null) {pageBean.setPs(list);}pageBean.setCategory(name);return pageBean;}/** * 分页查询,返回pageBean,pegeBean封装了当前页的所有信息 */@Overridepublic PageBean findPageBooks(int currentPage, int pageSize, String category) throws SQLException {// 1.获取当前类别下,一页显示pageSize条,当前页所对应的所有书籍ImplProductDao impl = new ImplProductDao();List<Product> products = impl.findBooks(currentPage, pageSize, category);// 2.获取当前类别下所有书籍的个数long totalcount = impl.count(category);//如果当前分类下 的图书个数为0,则currentPage为0if (totalcount == 0) {currentPage = 0;}// 3.计算要显示的总页数int totalpage = (int) Math.ceil(totalcount / (double) pageSize);// 4.创建PageBean对象PageBean pageBean = new PageBean();pageBean.setCurrentPage(currentPage);pageBean.setTotalCount(totalcount);pageBean.setTotalPage(totalpage);pageBean.setCurrentCount(pageSize);pageBean.setPs(products);pageBean.setCategory(category);return pageBean;}}





0 0
原创粉丝点击