荐 网上书城项目之书籍搜索、购物车的初步实现
网上书城项目
前言
今天为大家分享的知识点呢,是网上书城项目中的两个部分,书籍搜索页面的实现以及购物车的初步实现啦~
书籍搜索
书籍搜索呢,主要分为两个部分,左边部分是书籍分类部分,这个昨天的博客有详细说到过,所以就不再次细讲。
而右边部分的书籍具体信息展示,由于内容不多,所以适合用c:forEach标签的方式来遍历数据
有两种方式可以进行搜索:
一、根据关键字进行搜索
代码实现
search.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="w" uri="/wangqiuping"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>书籍搜索页</title>
<!-- 写全局样式 -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/themes/default/easyui.css">
<!-- 定义图标的样式 -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/themes/icon.css">
<!--组件库源文件的js文件-->
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/index.js"></script>
<title>首页</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/fg.css" />
</head>
<body>
<div class="container">
<!-- 横幅 -->
<div class="row">
<div class="col-sm-4">
您好,欢迎来到网上书城!
</div>
<div class="col-sm-4 col-sm-offset-4">
<a type="button" href="${pageContext.request.contextPath}/login.jsp">登录</a>
<a type="button" href="${pageContext.request.contextPath}/register.jsp">注册</a>
<a type="button" href="${pageContext.request.contextPath}/shoppingCar.jsp">我的购物车</a>
<a type="button" href="${pageContext.request.contextPath}/index.jsp">网站首页</a>
</div>
</div>
<!-- 搜索栏 -->
<div class="row">
<div class="col-sm-12 search-parent">
<!-- 本来这里应该放一张背景图的 -->
<div class="search"></div>
<input type="text" id="book_name" name="name" value="" />
<button onclick="search()" type="button" class="btn btn-primary">搜索</button>
</div>
</div>
<!-- 主内容区 -->
<div class="row content">
<div class="col-sm-3 l-content">
<ul class="list-group c-category "></ul>
</div>
<div class="col-sm-9">
<c:forEach items="${books}" var="b">
<div class="media">
<img src="${b.image}" class="align-self-center mr-3" alt="...">
<div class="media-body">
<p>${b.name}</p>
<p>作者:${b.author}</p>
<p>价格:¥ ${b.price}</p>
<p>出版社:${b.publishing}</p>
<p>简介:${b.description}</p>
<p>
<!-- <button class="btn btn-danger" onclick='addShopCar(this)' style="width: 150px;">加入购物车</button> -->
<a style="width: 150px;" class="btn btn-danger" href="${pageContext.request.contextPath}/shopping.action?methodName=add&name=${b.name}&price=${b.price}&num=1&total=${b.price}">加入购物车</a>
<button class="btn btn-danger" style="width: 150px;">去结算</button>
</p>
</div>
</div>
</c:forEach>
<!--调用分页标签 -->
<w:page pageBean="${pageBean}"></w:page>
</div>
</div>
</body>
</html>
jsp页面搜索的主要代码:
在button按钮下增加一个onclick点击事件
<!-- 搜索栏 -->
<div class="row">
<div class="col-sm-12 search-parent">
<!-- 本来这里应该放一张背景图的 -->
<div class="search"></div>
<input type="text" id="book_name" name="name" value="" />
<button onclick="search()" type="button" class="btn btn-primary">搜索</button>
</div>
</div>
index.js
点击事件应用到的js代码
//书籍搜索
function search(){
var ctx=$("#ctx").val();
location.href=ctx+"/book.action?methodName=search&name="+$("#book_name").val();
}
action层:
BookAction类
返回search页面 需要进行跳转 需要配置search结果码
package com.wangqiuping.action;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wangqiuping.dao.BookDao;
import com.wangqiuping.entity.Book;
import com.wangqiuping.framework.ActionSupport;
import com.wangqiuping.framework.ModelDriven;
import com.wangqiuping.util.DataGridResult;
import com.wangqiuping.util.PageBean;
import com.wangqiuping.util.ResponseUtil;
import com.wangqiuping.util.Result;
public class BookAction extends ActionSupport implements ModelDriven<Book>{
private Book book=new Book();
private BookDao bookDao=new BookDao();
@Override
public Book getModel() {
return book;
}
//书籍搜索
public String search(HttpServletRequest req,HttpServletResponse resp) throws Exception {
PageBean pageBean=new PageBean();
pageBean.setRequest(req);//给pageBean初始化
try {
List<Book> list = this.bookDao.search(book, pageBean);
req.setAttribute("books",list);
req.setAttribute("pageBean",pageBean);
}catch (InstantiationException e) {
e.printStackTrace();
}catch (IllegalAccessException e) {
e.printStackTrace();
}catch (SQLException e) {
}
return "search";
}
}
dao层:
BookDao类
给书籍名称增加判断,不为空则进行sql语句的拼接
package com.wangqiuping.dao;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.wangqiuping.entity.Book;
import com.wangqiuping.util.BaseDao;
import com.wangqiuping.util.PageBean;
import com.wangqiuping.util.PinYinUtil;
import com.wangqiuping.util.StringUtils;
public class BookDao extends BaseDao<Book>{
//书籍搜索
public List<Book> search(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String name=book.getName();//书名
long cid = book.getCid();//书籍类别id
String sql="select * from t_easyui_book where true";
if(StringUtils.isNotBlank(name)){
sql += " and name like'%"+name+"%'";
}
return executeQuery(sql,Book.class,pageBean);
}
}
entity层:
book类
package com.wangqiuping.entity;
import java.sql.Timestamp;
public class Book {
private long id;
private String name;
private String pinyin;
private long cid;
private String author;
private float price;
private String image;
private String publishing;
private String description;
private int state;
private Timestamp deployTime;
private int sales;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPinyin() {
return pinyin;
}
public void setPinyin(String pinyin) {
this.pinyin = pinyin;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPublishing() {
return publishing;
}
public void setPublishing(String publishing) {
this.publishing = publishing;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public Timestamp getDeployTime() {
return deployTime;
}
public void setDeployTime(Timestamp deployTime) {
this.deployTime = deployTime;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
public Book(long id, String name, String pinyin, long cid, String author, float price, String image, String publishing,
String description, int state, Timestamp deployTime, int sales) {
super();
this.id = id;
this.name = name;
this.pinyin = pinyin;
this.cid = cid;
this.author = author;
this.price = price;
this.image = image;
this.publishing = publishing;
this.description = description;
this.state = state;
this.deployTime = deployTime;
this.sales = sales;
}
public Book() {
super();
}
public Book(long id, String name, String pinyin) {
super();
this.id = id;
this.name = name;
this.pinyin = pinyin;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", pinyin=" + pinyin + ", cid=" + cid + ", author=" + author
+ ", price=" + price + ", image=" + image + ", publishing=" + publishing + ", description=" + description
+ ", state=" + state + ", deployTime=" + deployTime + ", sales=" + sales + "]";
}
}
效果
例如:我要搜索书名中含有"种子"的书籍
在文本框输入"种子",进行搜索后的效果:
二、根据书籍分类列表进行搜索
代码实现
jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="w" uri="/wangqiuping"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>书籍搜索页</title>
<!-- 写全局样式 -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/themes/default/easyui.css">
<!-- 定义图标的样式 -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/themes/icon.css">
<!--组件库源文件的js文件-->
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/index.js"></script>
<title>首页</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/fg.css" />
</head>
<body>
<div class="container">
<!-- 横幅 -->
<div class="row">
<div class="col-sm-4">
您好,欢迎来到网上书城!
</div>
<div class="col-sm-4 col-sm-offset-4">
<a type="button" href="${pageContext.request.contextPath}/login.jsp">登录</a>
<a type="button" href="${pageContext.request.contextPath}/register.jsp">注册</a>
<a type="button" href="${pageContext.request.contextPath}/shoppingCar.jsp">我的购物车</a>
<a type="button" href="${pageContext.request.contextPath}/index.jsp">网站首页</a>
</div>
</div>
<!-- 搜索栏 -->
<div class="row">
<div class="col-sm-12 search-parent">
<!-- 本来这里应该放一张背景图的 -->
<div class="search"></div>
<input type="text" id="book_name" name="name" value="" />
<button onclick="search()" type="button" class="btn btn-primary">搜索</button>
</div>
</div>
<!-- 主内容区 -->
<div class="row content">
<div class="col-sm-3 l-content">
<ul class="list-group c-category ">
</ul>
</div>
<div class="col-sm-9">
<c:forEach items="${books}" var="b">
<div class="media">
<img src="${b.image}" class="align-self-center mr-3" alt="...">
<div class="media-body">
<p>${b.name}</p>
<p>作者:${b.author}</p>
<p>价格:¥ ${b.price}</p>
<p>出版社:${b.publishing}</p>
<p>简介:${b.description}</p>
<p>
<!-- <button class="btn btn-danger" onclick='addShopCar(this)' style="width: 150px;">加入购物车</button> -->
<a style="width: 150px;" class="btn btn-danger" href="${pageContext.request.contextPath}/shopping.action?methodName=add&name=${b.name}&price=${b.price}&num=1&total=${b.price}">加入购物车</a>
<button class="btn btn-danger" style="width: 150px;">去结算</button>
</p>
</div>
</div>
</c:forEach>
<!--调用分页标签 -->
<w:page pageBean="${pageBean}"></w:page>
</div>
</div>
</body>
</html>
jsp页面中书籍分类的主要代码:
<div class="row content">
<div class="col-sm-3 l-content">
<ul class="list-group c-category ">
<li class="list-group-item" style="color: white;">书籍分类</li>
</ul>
</div>
action层:
BookAction类
package com.wangqiuping.action;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wangqiuping.dao.BookDao;
import com.wangqiuping.entity.Book;
import com.wangqiuping.framework.ActionSupport;
import com.wangqiuping.framework.ModelDriven;
import com.wangqiuping.util.DataGridResult;
import com.wangqiuping.util.PageBean;
import com.wangqiuping.util.ResponseUtil;
import com.wangqiuping.util.Result;
public class BookAction extends ActionSupport implements ModelDriven<Book>{
private Book book=new Book();
private BookDao bookDao=new BookDao();
@Override
public Book getModel() {
return book;
}
//书籍搜索
public String search(HttpServletRequest req,HttpServletResponse resp) throws Exception {
PageBean pageBean=new PageBean();
pageBean.setRequest(req);//给pageBean初始化
try {
List<Book> list = this.bookDao.search(book, pageBean);
req.setAttribute("books",list);
req.setAttribute("pageBean",pageBean);
}catch (InstantiationException e) {
e.printStackTrace();
}catch (IllegalAccessException e) {
e.printStackTrace();
}catch (SQLException e) {
}
return "search";
}
}
dao层:
BookDao类
给书籍类别增加判断,如果类别不为空,则进行sql语句的拼接
//书籍搜索
public List<Book> search(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String name=book.getName();//书名
long cid = book.getCid();//书籍类别id
String sql="select * from t_easyui_book where true";
if(cid!=0) {
sql += " and cid="+cid;
}
return executeQuery(sql,Book.class,pageBean);
}
index.js
加载左侧书籍分类,并且调用searchByType(cid)函数进行按照书籍类别查询的操作
$(function(){
var ctx=$("#ctx").val();
//加载左侧书籍类别
$.ajax({
url:ctx+'/categroy.action?methodName=comboBox',
success:function(data){//使用success的回调函数
data=eval('('+data+')');//得到的是一个josn对象
//debugger;
//alert(data);
//<li class="list-group-item">现代言情</li>
for(i in data){
$(".list-group").append('<li class="list-group-item" οnclick="searchByType('+data[i].id+')">'+data[i].name+'</li>');
$(".c-category li").eq(0).addClass('bg-color1');
$(".c-category li:gt(0)").addClass('bg-color2');
$(".c-category li:gt(0)").hover(function() {
$(this).addClass('bg-opacity');
},function() {
$(this).removeClass('bg-opacity');
});
}
}
});
//按照书籍类别搜索
function searchByType(cid){
var ctx=$("#ctx").val();
location.href=ctx+"/book.action?methodName=search&cid="+cid;
}
效果
例如:我要查询"小说"类别的书籍:
按照类别查询后,会展示出与小说对应的书籍:
购物车的初步实现
该购物车主要使用application进行存储,不需要使用数据库,并且没有dao方法,相较于session和cookie版本的购物车而言,不需要设置有效时间,并且范围大
代码实现
search.jsp页面
给加入购物车按钮增加点击事件
获取加入购物车时书籍的相关书籍
传参数并跳转页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="w" uri="/wangqiuping"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>书籍搜索页</title>
<!-- 写全局样式 -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/themes/default/easyui.css">
<!-- 定义图标的样式 -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/themes/icon.css">
<!--组件库源文件的js文件-->
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/index.js"></script>
<title>首页</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/fg.css" />
</head>
<body>
<div class="container">
<!-- 横幅 -->
<div class="row">
<div class="col-sm-4">
您好,欢迎来到网上书城!
</div>
<div class="col-sm-4 col-sm-offset-4">
<a type="button" href="${pageContext.request.contextPath}/login.jsp">登录</a>
<a type="button" href="${pageContext.request.contextPath}/register.jsp">注册</a>
<a type="button" href="${pageContext.request.contextPath}/shoppingCar.jsp">我的购物车</a>
<a type="button" href="${pageContext.request.contextPath}/index.jsp">网站首页</a>
</div>
</div>
<!-- 搜索栏 -->
<div class="row">
<div class="col-sm-12 search-parent">
<!-- 本来这里应该放一张背景图的 -->
<div class="search"></div>
<input type="text" id="book_name" name="name" value="" />
<button onclick="search()" type="button" class="btn btn-primary">搜索</button>
</div>
</div>
<!-- 主内容区 -->
<div class="row content">
<div class="col-sm-3 l-content">
<ul class="list-group c-category "></ul>
</div>
<div class="col-sm-9">
<c:forEach items="${books}" var="b">
<div class="media">
<img src="${b.image}" class="align-self-center mr-3" alt="...">
<div class="media-body">
<p>${b.name}</p>
<p>作者:${b.author}</p>
<p>价格:¥ ${b.price}</p>
<p>出版社:${b.publishing}</p>
<p>简介:${b.description}</p>
<p>
<!-- <button class="btn btn-danger" onclick='addShopCar(this)' style="width: 150px;">加入购物车</button> -->
<a style="width: 150px;" class="btn btn-danger" href="${pageContext.request.contextPath}/shopping.action?methodName=add&name=${b.name}&price=${b.price}&num=1&total=${b.price}">加入购物车</a>
<button class="btn btn-danger" style="width: 150px;">去结算</button>
</p>
</div>
</div>
</c:forEach>
<!--调用分页标签 -->
<w:page pageBean="${pageBean}"></w:page>
</div>
</div>
</body>
</html>
action层:
ShoppingAction类
用来获取jsp页面的用add方法实现加入购物车的操作
需要给不同用户增加id进行辨别
package com.wangqiuping.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wangqiuping.entity.User;
import com.wangqiuping.framework.ActionSupport;
import com.wangqiuping.framework.ModelDriven;
import com.wangqiuping.util.StringUtils;
import com.wangqiuping.vo.ShoppingVo;
public class ShoppingAction extends ActionSupport implements ModelDriven<ShoppingVo>{
private ShoppingVo shoppingVo=new ShoppingVo();
@Override
public ShoppingVo getModel() {
// TODO Auto-generated method stub
return shoppingVo;
}
//加入购物车
public String add(HttpServletRequest req,HttpServletResponse resp) {
ServletContext ctx = req.getServletContext();
//给每个用户添加一个购物车,根据id进行分辨
String Shopcar="shopcars_";
User currentUser = (User) req.getSession().getAttribute("currentUser");
//在application中不存储list集合,存储json字符串
List<ShoppingVo> Shopcars = (List<ShoppingVo>) ctx.getAttribute(Shopcar+currentUser.getId());
if(Shopcars==null||Shopcars.size()==0) {
//第一次添加时,购物车中没有商品
Shopcars=new ArrayList<ShoppingVo>();
}else {
//第二次添加,购物车里有商品
}
Shopcars.add(shoppingVo);
//jdk 1.5
Shopcars.forEach(System.out::println);
ctx.setAttribute("Shopcars",Shopcars);
return "shoppingCar";
}
}
ShoppingVo类
相当于实体类
用来展示购物车列表订单项所需数据
里面放set/get方法、无参、有参构造器以及toString方法
package com.wangqiuping.vo;
import java.util.Objects;
public class ShoppingVo {
private String name;
private float price;
private int num;
private float total;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
public ShoppingVo() {
super();
}
public ShoppingVo(String name, float price, int num, float total) {
super();
this.name = name;
this.price = price;
this.num = num;
this.total = total;
}
@Override
public String toString() {
return "ShoppingVo [name=" + name + ", price=" + price + ", num=" + num + ", total=" + total + "]";
}
}
mxc.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<config>
<!-- 默认重定向 -->
<!--书籍-->
<action path="/book" type="com.wangqiuping.action.BookAction">
<forward name="search" path="/fg/search.jsp" redirect="false" />
</action>
<!--用户操作 -->
<action path="/user" type="com.wangqiuping.action.UserAction">
<forward name="login" path="/login.jsp" redirect="false"/>
<forward name="main" path="/bg/main.jsp" redirect="false"/>
</action>
<!--书籍类别加载 -->
<action path="/categroy" type="com.wangqiuping.action.CategroyAction">
</action>
<!--购物车 -->
<action path="/shopping" type="com.wangqiuping.action.ShoppingAction">
<forward name="shoppingCar" path="/fg/shoppingCar.jsp" redirect="false"/>
</action>
</config>
效果
举例:把"斗破苍穹"这本书籍加入到购物车
点击"斗破苍穹"下的加入购物车按钮即可
注意要点
1、用户在执行加入购物车的操作时,需要进行登录,否则执行后的操作是这样子的,会显示空白,什么内容也没有
并且eclipse中也会提示空指针异常:
提示这一行的代码内容为空
List<ShoppingVo> Shopcars = (List<ShoppingVo>)
ctx.getAttribute(Shopcar+currentUser.getId());
其实是没有获取到用户的id,所以进行登录后再执行加入购物车的操作就好
2、mvc.xml中结果码的配置要和action层中返回结果保持一致!
3、配置结果码之前,先思考是否需要进行重定向还是转发,或者是返回json数据进行页面的无刷新!
总结
书籍类别和加入购物车的操作就分享到这,编码的过程需先思考再动手,测试的时候注意思路和细节,因为可能编码不一定一次就成功啦,欢迎评论留言交流哦,拜拜~
本文地址:https://blog.csdn.net/qq_45464930/article/details/107215197
下一篇: 【知道/智慧树】网课刷题·最终版本