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

1.实现效果图

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

2.home.jsp,主页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


	
		
		bootstore
		
		
		
		
		
		
		
		
		
		
		
		
	
	
		
		
		<%@include file="/foreground/common/head.jsp"%>
		
		
		
		
		

新书上架

JAVA入门经典

《Java入门经典》,是2012年出版的图书,是2012年出版的图书是2012年出版的图书作者是Rogers Cadenhead。 《Java入门经典(第6版)》总共24章,先讲解了Java程序的编写流程、工作原理等内容;然后介绍了有关Java编程 的基本知识,包括变量、条件语句、

本周热卖


书名:java核心技术
售价:XXX

书名:javascript
售价:XXX

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 +="
" + ss[i] + "
"; } //显示搜索框 $("#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" %>


	
		
		bookcategory
		
		
		
		
		
		
		
		
		
		
	
	
		
		
		<%@include file="/foreground/common/head.jsp"%>
		
		
		
		

书名:${book.name}
售价:${book.price}


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 list = implProductDao.findBooksByBlurName(value);
			//3.把所有符合条件的书拼接成字符串
			String books = "";
			if("".equals(value)){
				
			}else{
				for(int i = 0;i0){
						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 findAllBooks() throws SQLException;
	//根据书的id查找指定的书籍
	public Product findBookById(String id) throws SQLException;
	//查找某一分类下的书籍总数
	public long count(String category) throws SQLException;
	//分页查询,查找当前页下、每页显示指定size下、以及当前分类下的书籍
	public List findBooks(int currentPage, int pageSize,String category) throws SQLException;
	//根据指定书名搜索书籍
	public Product searchBookByName(String name) throws SQLException;
	//模糊检索,根据模糊条件查找数据库,返回list集合
	public List 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 findAllBooks() throws SQLException {
		//1.创建QueryRunner对象
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		List 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.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 findBooks(int currentPage, int pageSize, String category) throws SQLException {
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		String sql = null;
		List 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.class),name);
		return product;
	}

	/**
	 * 模糊检索,根据模糊条件查找数据库,返回list
	 */
	@Override
	public List findBooksByBlurName(String name) throws SQLException {
		//1.创建QueryRunner对象
		QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
		List 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 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 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;
	}

}





你可能感兴趣的:(项目)