图书购买系统之商品分类分页--根据主页面传来的值分类显示商品并实现动态分页功能_html 代码实现分类的书籍列表页-程序员宅基地

技术标签: 分页  项目  图书实时检索  

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" οnclick="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 οnclick='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" οnclick="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.判断我们存的书籍是否已经在购物车了,如果存在,数量+1
		var 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;
	//模糊检索,根据模糊条件查找数据库,返回pageBean
	public 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{

	/**
	 * 查找所有的书籍
	 */
	@Override
	public 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查找指定的书籍
	 */
	@Override
	public 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;
	}

	/**
	 * 查找某一分类下的书籍总数
	 */
	@Override
	public 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下、以及当前分类下的所有书籍
	 */
	@Override
	public 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;
	}

	/**
	 * 根据指定书名搜索书籍
	 */
	@Override
	public 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
	 */
	@Override
	public 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")
	@Override
	public 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封装了当前页的所有信息
	 */
	@Override
	public 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为0
		if (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;
	}

}





版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/java_jfei/article/details/70036928

智能推荐

c# 调用c++ lib静态库_c#调用lib-程序员宅基地

文章浏览阅读2w次,点赞7次,收藏51次。四个步骤1.创建C++ Win32项目动态库dll 2.在Win32项目动态库中添加 外部依赖项 lib头文件和lib库3.导出C接口4.c#调用c++动态库开始你的表演...①创建一个空白的解决方案,在解决方案中添加 Visual C++ , Win32 项目空白解决方案的创建:添加Visual C++ , Win32 项目这......_c#调用lib

deepin/ubuntu安装苹方字体-程序员宅基地

文章浏览阅读4.6k次。苹方字体是苹果系统上的黑体,挺好看的。注重颜值的网站都会使用,例如知乎:font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, PingFang SC, Microsoft YaHei, Source Han Sans SC, Noto Sans CJK SC, W..._ubuntu pingfang

html表单常见操作汇总_html表单的处理程序有那些-程序员宅基地

文章浏览阅读159次。表单表单概述表单标签表单域按钮控件demo表单标签表单标签基本语法结构<form action="处理数据程序的url地址“ method=”get|post“ name="表单名称”></form><!--action,当提交表单时,向何处发送表单中的数据,地址可以是相对地址也可以是绝对地址--><!--method将表单中的数据传送给服务器处理,get方式直接显示在url地址中,数据可以被缓存,且长度有限制;而post方式数据隐藏传输,_html表单的处理程序有那些

PHP设置谷歌验证器(Google Authenticator)实现操作二步验证_php otp 验证器-程序员宅基地

文章浏览阅读1.2k次。使用说明:开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。下载谷歌验证类库文件放到项目合适位置(我这边放在项目Vender下面)https://github.com/PHPGangsta/GoogleAuthenticatorPHP代码示例://引入谷_php otp 验证器

【Python】matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距-程序员宅基地

文章浏览阅读4.3k次,点赞5次,收藏11次。matplotlib.plot画图横坐标混乱及间隔处理_matplotlib更改横轴间距

docker — 容器存储_docker 保存容器-程序员宅基地

文章浏览阅读2.2k次。①Storage driver 处理各镜像层及容器层的处理细节,实现了多层数据的堆叠,为用户 提供了多层数据合并后的统一视图②所有 Storage driver 都使用可堆叠图像层和写时复制(CoW)策略③docker info 命令可查看当系统上的 storage driver主要用于测试目的,不建议用于生成环境。_docker 保存容器

随便推点

网络拓扑结构_网络拓扑csdn-程序员宅基地

文章浏览阅读834次,点赞27次,收藏13次。网络拓扑结构是指计算机网络中各组件(如计算机、服务器、打印机、路由器、交换机等设备)及其连接线路在物理布局或逻辑构型上的排列形式。这种布局不仅描述了设备间的实际物理连接方式,也决定了数据在网络中流动的路径和方式。不同的网络拓扑结构影响着网络的性能、可靠性、可扩展性及管理维护的难易程度。_网络拓扑csdn

JS重写Date函数,兼容IOS系统_date.prototype 将所有 ios-程序员宅基地

文章浏览阅读1.8k次,点赞5次,收藏8次。IOS系统Date的坑要创建一个指定时间的new Date对象时,通常的做法是:new Date("2020-09-21 11:11:00")这行代码在 PC 端和安卓端都是正常的,而在 iOS 端则会提示 Invalid Date 无效日期。在IOS年月日中间的横岗许换成斜杠,也就是new Date("2020/09/21 11:11:00")通常为了兼容IOS的这个坑,需要做一些额外的特殊处理,笔者在开发的时候经常会忘了兼容IOS系统。所以就想试着重写Date函数,一劳永逸,避免每次ne_date.prototype 将所有 ios

如何将EXCEL表导入plsql数据库中-程序员宅基地

文章浏览阅读5.3k次。方法一:用PLSQL Developer工具。 1 在PLSQL Developer的sql window里输入select * from test for update; 2 按F8执行 3 打开锁, 再按一下加号. 鼠标点到第一列的列头,使全列成选中状态,然后粘贴,最后commit提交即可。(前提..._excel导入pl/sql

Git常用命令速查手册-程序员宅基地

文章浏览阅读83次。Git常用命令速查手册1、初始化仓库git init2、将文件添加到仓库git add 文件名 # 将工作区的某个文件添加到暂存区 git add -u # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,不处理untracked的文件git add -A # 添加所有被tracked文件中被修改或删除的文件信息到暂存区,包括untracked的文件...

分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120-程序员宅基地

文章浏览阅读202次。分享119个ASP.NET源码总有一个是你想要的_千博二手车源码v2023 build 1120

【C++缺省函数】 空类默认产生的6个类成员函数_空类默认产生哪些类成员函数-程序员宅基地

文章浏览阅读1.8k次。版权声明:转载请注明出处 http://blog.csdn.net/irean_lau。目录(?)[+]1、缺省构造函数。2、缺省拷贝构造函数。3、 缺省析构函数。4、缺省赋值运算符。5、缺省取址运算符。6、 缺省取址运算符 const。[cpp] view plain copy_空类默认产生哪些类成员函数

推荐文章

热门文章

相关标签