图书购买系统之商品分类分页--根据主页面传来的值分类显示商品并实现动态分页功能_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

智能推荐

为什么网络安全人口很稀缺,招聘人数却很少?_网络安全招聘少-程序员宅基地

文章浏览阅读101次。2020年我国网络空间安全人才数量缺口超过了140万,就业人数却只有10多万,缺口高达了93%。这里就有人会问了:1、网络安全行业为什么这么缺人?2、明明人才那么稀缺,为什么招聘时招安全的人员却没有那么多呢?首先来回答第一个问题,从政策背景、市场需求、行业现状来说。自从斯诺登棱镜门事件曝光之后,网络空间站成为现代战场第一战场,网络安全能力也被各国列为了必要的发展战略。上到政府、下到企业、个人,大家对网络安全的关注迅速提升。公安部推出了网络安全等级保护制度,网信办推出了《网络安全法》等诸多法规。_网络安全招聘少

python文本数据处理_用python处理文本数据 学到的一些东西-程序员宅基地

文章浏览阅读94次。最近写了一个python脚本,用TagMe的api标注文本,并解析返回的json数据。在这个过程中遇到了很多问题,学到了一些新东西,总结一下。1. csv文件处理csv是一种格式化的文件,由行和列组成,分隔符可以根据需要发生变化。只有分隔符为逗号','时,才会在excel中显示为列。python的csv模块提供了reader和writer函数来读写csv格式的数据。csv.reader(csvfi..._tagme python

这些年职业爬虫师教会我的技巧(一)-程序员宅基地

文章浏览阅读309次。阅读文本大概需要 4 分钟。随着 Python 越来越火爆爬虫这个行业也逐渐被人所重视起来,但市面上教的一些爬虫的技巧大多是一些基础类的知识,然而在实际的爬虫工作中你会遇..._爬虫师

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war-程序员宅基地

文章浏览阅读5k次。完美解决方案:http://stackoverflow.com/questions/18442753/a-required-class-was-missing-while-executing-org-apache-maven-pluginsmaven-warthis happened to me too after adding the version tag, that was mi..._a required class was missing while executing org.apache.maven.plugins:maven-

常见的电平标准 USB/TTL/RS232/RS485_usb电平标准-程序员宅基地

文章浏览阅读1.9w次,点赞13次,收藏75次。RS232电平或者说串口电平:指得都是计算机9针串口的电平,采用负逻辑:-15v ~ -3v 代表1 ,+3v ~ +15v 代表0 。RS485电平和RS422电平:由于两者均采用差分传输(平衡传输)的方式,所以它们的电平方式,一般有两个引脚 A,B 发送端 AB间的电势差U为UB-UA: +2 ~ +6v : 1 ,-2 ~ -6v : 0 ,接收端 AB间的电势差U为:大于 +200_usb电平标准

mysql+pivot+列转行_sql的行转列(PIVOT)与列转行(UNPIVOT)-程序员宅基地

文章浏览阅读1.5k次。CREATE TABLE [StudentScores]([UserName] NVARCHAR(20), --学生姓名[Subject] NVARCHAR(30), --科目[Score] FLOAT, --成绩)INSERT INTO [StudentScores] SELECT ..._mysql pivot

随便推点

刀片式服务器市场破局者——浪潮I9000解决企业用户需求痛点-程序员宅基地

文章浏览阅读173次。在x86服务器市场中,刀片服务器一直以来都是一股不可小视的重要力量。据IDC的数据报告显示,在2015年,刀片服务器在诸多大型行业中具有较高的需求量:金融行业为15%,电信行业为14%,能源行业为12%,政府、制造及交通行业也均达10%,刀片服务器已经成为企业级客户的重要选择。企业级市场对刀片服务器青睐有加服务器在空间和电费方面的花费占到运营成本的5..._服务器工业设计痛点问题

Keil生成bin文件:fromelf.exe --bin -o “[email protected]“ “#L“_fromelf.exe --bin -o "[email protected]" "#l"生成的是文件夹怎么修改-程序员宅基地

文章浏览阅读256次。Keil生成bin文件:fromelf.exe --bin -o "[email protected]" "#L" 不受工程移植路径和工程名的影响,通用。_fromelf.exe --bin -o "[email protected]" "#l"生成的是文件夹怎么修改

STM32G030F6P6 芯片实验 (一)_stm32g030f6p6 晶振-程序员宅基地

文章浏览阅读878次。搞片小系统版: 套 STM32F103C8T6小系统板格式. M0+, 试试感觉. _stm32g030f6p6 晶振

云上更安全?亚马逊云科技宣布将持续加大在中国区域安全合规领域投入-程序员宅基地

文章浏览阅读5.3k次。编辑 | 宋慧出品 | CSDN云计算新冠疫情对我们工作产生了深远的影响,远程在线的工作与交流愈加普及,国内更多公司在推出居家办公的“混合办公”模式。不过,这也给了网络攻击更多的机会,CSDN看到,有多个安全领域的报告都显示,针对身份和边缘的攻击与安全风险正在不断增加,云上安全备受关注。近日,亚马逊云科技宣布将持续加大在中国区域安全合规领域的投入,在为客户提供安全合规的基础设施和云服务基础上,将与光环新网及西云数据共同加速安全合规服务和功能在中国的落地,并进一步加强与亚马逊云科技合作伙伴

java只有值传递没有引用传递_普通数据类型为什么不能进行引用传递-程序员宅基地

文章浏览阅读191次。java中的参数传递不管是基本数据类型还是引用 数据类型只有值传递,没有引用传递,也就是说Java中参数传递的是内容,而不是引用。下面看几个例子。例1:/* 1. 基本数据类型的参数传递 2. */package ch.demo2;public class TestDemo1 { public static void main(String[] args) { int a = 5..._普通数据类型为什么不能进行引用传递

linux 下多线程错误 undefined reference to `sem_init'_undefined reference to `sem_post-程序员宅基地

文章浏览阅读7.3k次,点赞7次,收藏8次。原文地址::http://www.cnblogs.com/stli/archive/2010/03/11/1683823.htmlundefined reference to `sem_init'undefined reference to `sem_post'undefined reference to `sem_wait'编译选项需要加入一个多线程g_undefined reference to `sem_post

推荐文章

热门文章

相关标签