SSH网上商城四
第29课:10-SSH网上商城:购物模块的实体的封装
1、现在我们要实现购物车的模块,当用户在点击

加入购物车按钮的时候需要跳转到

上面我们需要对购物车的对象进行封装
上面一个商品就对应一个记录项,购物车中可以购买不同的商品,对应多个记录项,每一个记录项应该包含当前商品的信息,购买的数量 已经小计

我们来看具体对应的封装的实体类
package cn.itcast.shop.cart.beans; import cn.itcast.shop.product.beans.Product; /**
* 购物项对象
* @author 传智.郭嘉
*
*/
public class CartItem {
private Product product; // 购物项中商品信息
private int count; // 购买某种商品数量
private double subtotal; // 购买某种商品小计
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
// 小计自动计算的.
public double getSubtotal() {
return count * product.getShop_price();
}
/*public void setSubtotal(double subtotal) {
this.subtotal = subtotal;
}
*/ }
package cn.itcast.shop.cart.beans; import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map; /**
* 购物车对象
*
* @author 传智.郭嘉
*
*/
public class Cart implements Serializable{
// 购物车属性
// 购物项集合:Map的key就是商品pid,value:购物项
private Map<Integer, CartItem> map = new LinkedHashMap<Integer, CartItem>(); // Cart对象中有一个叫cartItems属性.
public Collection<CartItem> getCartItems(){
return map.values();
} // 购物总计:
private double total; public double getTotal() {
return total;
} // 购物车的功能:
// 1.将购物项添加到购物车
public void addCart(CartItem cartItem) {
// 判断购物车中是否已经存在该购物项:
/*
* * 如果存在:
* * 数量增加
* * 总计 = 总计 + 购物项小计
* * 如果不存在:
* * 向map中添加购物项
* * 总计 = 总计 + 购物项小计
*/
// 获得商品id.
Integer pid = cartItem.getProduct().getPid();
// 判断购物车中是否已经存在该购物项:
if(map.containsKey(pid)){
// 存在
CartItem _cartItem = map.get(pid);// 获得购物车中原来的购物项
_cartItem.setCount(_cartItem.getCount()+cartItem.getCount());
}else{
// 不存在
map.put(pid, cartItem);
}
// 设置总计的值
total += cartItem.getSubtotal();
} // 2.从购物车移除购物项
public void removeCart(Integer pid) {
// 将购物项移除购物车:
CartItem cartItem = map.remove(pid);
// 总计 = 总计 -移除的购物项小计:
total -= cartItem.getSubtotal();
} // 3.清空购物车
public void clearCart() {
// 将所有购物项清空
map.clear();
// 将总计设置为0
total = 0;
}
}
这里需要注意的是在购物车的Cart类中封装了一个方法
// Cart对象中有一个叫cartItems属性.
public Collection<CartItem> getCartItems(){
return map.values();
}
将购物车的购物项封装成一个set集合,这样在jsp页面的时候就可以对cartItems集合进行遍历,相当于在Cart类之后定义一个cartItems成员变量,提供了外界可以访问的get方法
接下来实现下面的功能:

我们点击的加入购物车的时候,需要跳转到对应的CartAction进行处理,并且要传递当前购买的数目过去,当前商品的ip
我们首先找到product.jsp页面,用户点击加入购物车的按钮
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>网上商城</title>
<link href="${pageContext.request.contextPath}/css/common.css" rel="stylesheet" type="text/css"/>
<link href="${pageContext.request.contextPath}/css/product.css" rel="stylesheet" type="text/css"/>
<script>
function saveCart(){
document.getElementById("cartForm").submit();
}
</script> </head>
<body> <div class="container header">
<div class="span5">
<div class="logo">
<a>
<img src="${pageContext.request.contextPath}/image/r___________renleipic_01/logo.gif" alt="传智播客">
</a>
</div>
</div>
<div class="span9">
<div class="headerAd">
<img src="data:image\r___________renleipic_01/header.jpg" alt="正品保障" title="正品保障" height="50" width="320">
</div> </div> <%@ include file="menu.jsp" %> </div><div class="container productContent">
<div class="span6">
<div class="hotProductCategory">
<s:iterator var="c" value="#session.cList">
<dl>
<dt>
<a href="${ pageContext.request.contextPath }/product_findByCid.action?cid=<s:property value="#c.cid"/>&page=1"><s:property value="#c.cname"/></a>
</dt>
<s:iterator var="cs" value="#c.categorySeconds">
<dd>
<a href="${ pageContext.request.contextPath }/product_findByCsid.action?csid=<s:property value="#cs.csid"/>&page=1"><s:property value="#cs.csname"/></a>
</dd>
</s:iterator>
</dl>
</s:iterator>
</div> </div> <div class="span18 last"> <div class="productImage">
<a title="" style="outline-style: none; text-decoration: none;" id="zoom" href="http://image/r___________renleipic_01/bigPic1ea8f1c9-8b8e-4262-8ca9-690912434692.jpg" rel="gallery">
<div class="zoomPad"><img style="opacity: 1;" title="" class="medium" src="${ pageContext.request.contextPath }/<s:property value="model.image"/>"><div style="display: block; top: 0px; left: 162px; width: 0px; height: 0px; position: absolute; border-width: 1px;" class="zoomPup"></div><div style="position: absolute; z-index: 5001; left: 312px; top: 0px; display: block;" class="zoomWindow"><div style="width: 368px;" class="zoomWrapper"><div style="width: 100%; position: absolute; display: none;" class="zoomWrapperTitle"></div><div style="width: 0%; height: 0px;" class="zoomWrapperImage"><img src="%E5%B0%9A%E9%83%BD%E6%AF%94%E6%8B%89%E5%A5%B3%E8%A3%852013%E5%A4%8F%E8%A3%85%E6%96%B0%E6%AC%BE%E8%95%BE%E4%B8%9D%E8%BF%9E%E8%A1%A3%E8%A3%99%20%E9%9F%A9%E7%89%88%E4%BF%AE%E8%BA%AB%E9%9B%AA%E7%BA%BA%E6%89%93%E5%BA%95%E8%A3%99%E5%AD%90%20%E6%98%A5%E6%AC%BE%20-%20Powered%20By%20Mango%20Team_files/6d53c211-2325-41ed-8696-d8fbceb1c199-large.jpg" style="position: absolute; border: 0px none; display: block; left: -432px; top: 0px;"></div></div></div><div style="visibility: hidden; top: 129.5px; left: 106px; position: absolute;" class="zoomPreload">Loading zoom</div></div>
</a> </div>
<div class="name"><s:property value="model.pname"/></div>
<div class="sn">
<div>编号:<s:property value="model.pid"/></div>
</div>
<div class="info">
<dl>
<dt>商城价:</dt>
<dd>
<strong>¥:<s:property value="model.shop_price"/>元</strong>
参 考 价:
<del>¥<s:property value="model.market_price"/>元</del>
</dd>
</dl>
<dl>
<dt>促销:</dt>
<dd>
<a target="_blank" title="限时抢购 (2014-07-30 ~ 2015-01-01)">限时抢购</a>
</dd>
</dl>
<dl>
<dt> </dt>
<dd>
<span> </span>
</dd>
</dl>
</div>
<form id="cartForm" action="${ pageContext.request.contextPath }/cart_addCart.action" method="post" >
<input type="hidden" name="pid" value="<s:property value="model.pid"/>"/>
<div class="action">
<dl class="quantity">
<dt>购买数量:</dt>
<dd>
<input id="count" name="count" value="1" maxlength="4" onpaste="return false;" type="text"/>
</dd>
<dd>
件
</dd>
</dl> <div class="buy">
<input id="addCart" class="addCart" value="加入购物车" type="button" onclick="saveCart()"/>
</div>
</div>
</form>
<div id="bar" class="bar">
<ul>
<li id="introductionTab">
<a href="#introduction">商品介绍</a>
</li> </ul>
</div> <div id="introduction" name="introduction" class="introduction">
<div class="title">
<strong><s:property value="model.pdesc"/></strong>
</div>
<div>
<img src="${pageContext.request.contextPath }/<s:property value="model.image"/>">
</div>
</div> </div>
</div>
<div class="container footer">
<div class="span24">
<div class="footerAd">
<img src="data:image\r___________renleipic_01/footer.jpg" alt="我们的优势" title="我们的优势" height="52" width="950">
</div>
</div>
<div class="span24">
<ul class="bottomNav">
<li>
<a href="#">关于我们</a>
|
</li>
<li>
<a href="#">联系我们</a>
|
</li>
<li>
<a href="#">诚聘英才</a>
|
</li>
<li>
<a href="#">法律声明</a>
|
</li>
<li>
<a>友情链接</a>
|
</li>
<li>
<a target="_blank">支付方式</a>
|
</li>
<li>
<a target="_blank">配送方式</a>
|
</li>
<li>
<a >SHOP++官网</a>
|
</li>
<li>
<a>SHOP++论坛</a> </li>
</ul>
</div>
<div class="span24">
<div class="copyright">Copyright © 2005-2015 网上商城 版权所有</div>
</div>
</div>
</body>
</html>
接下来我们来传递到cart_addCart.action这个cart对应的action进行处理,对应的方法是addCart,该action中需要接受传递过来的商品pid,传递过来的购买的数目等
在action中需要依据商品的pid值查询得到商品的信息需要引入private ProductService productService;
我们来看看对应的代码
package cn.itcast.shop.cart.action; import org.apache.struts2.ServletActionContext; import cn.itcast.shop.cart.beans.Cart;
import cn.itcast.shop.cart.beans.CartItem;
import cn.itcast.shop.product.beans.Product;
import cn.itcast.shop.product.service.ProductService; import com.opensymphony.xwork2.ActionSupport; /**
* 购物车Action
*
* @author 传智.郭嘉
*
*/
public class CartAction extends ActionSupport {
// 接收pid
private Integer pid;
// 接收数量count
private Integer count;
// 注入商品的Service
private ProductService productService; public void setProductService(ProductService productService) {
this.productService = productService;
} public void setPid(Integer pid) {
this.pid = pid;
} public void setCount(Integer count) {
this.count = count;
} // 将购物项添加到购物车:执行的方法
public String addCart() {
// 封装一个CartItem对象.
CartItem cartItem = new CartItem();
// 设置数量:
cartItem.setCount(count);
// 根据pid进行查询商品:
Product product = productService.findByPid(pid);
// 设置商品:
cartItem.setProduct(product);
// 将购物项添加到购物车.
// 购物车应该存在session中.
Cart cart = getCart();
cart.addCart(cartItem); return "addCart";
} // 清空购物车的执行的方法:
public String clearCart(){
// 获得购物车对象.
Cart cart = getCart();
// 调用购物车中清空方法.
cart.clearCart();
return "clearCart";
} // 从购物车中移除购物项的方法:
public String removeCart(){
// 获得购物车对象
Cart cart = getCart();
// 调用购物车中移除的方法:
cart.removeCart(pid);
// 返回页面:
return "removeCart";
} // 我的购物车:执行的方法
public String myCart(){
return "myCart";
} /**
* 获得购物车的方法:从session中获得购物车.
* @return
*/
private Cart getCart() {
Cart cart = (Cart) ServletActionContext.getRequest().getSession()
.getAttribute("cart");
if (cart == null) {
cart = new Cart();
ServletActionContext.getRequest().getSession()
.setAttribute("cart", cart);
}
return cart;
}
}
记得要在applicationContext-action.xml配置其生命周期
<!-- 购物车的Action -->
<bean id="cartAction" class="cn.itcast.shop.cart.action.CartAction" scope="prototype">
<property name="productService" ref="productService"/>
</bean>
整个applicationContext-action.xml的代码为:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 为了保证一个action对应一个线程,这里必须要配置scope="prototype" --> <!-- 跳转到用户首页的action -->
<bean id="indexAction" class="cn.itcast.shop.index.action.IndexAction" scope="prototype">
<property name="categoryService" ref="categoryService"></property>
<property name="productService" ref="productService"></property>
</bean> <bean id="userAction" class = "cn.itcast.shop.user.action.UserAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean>
<!-- 用于获得验证码的action进行验证 -->
<bean id = "checkImg" class = "cn.itcast.shop.user.action.CheckImgAction" scope="prototype"></bean> <bean id="productAction" class = "cn.itcast.shop.product.action.ProductAction" scope="prototype">
<property name="productService" ref="productService"></property>
<property name="categoryService" ref="categoryService"></property>
</bean> <!-- 购物车的Action -->
<bean id="cartAction" class="cn.itcast.shop.cart.action.CartAction" scope="prototype">
<property name="productService" ref="productService"/>
</bean> </beans>
对应的在struct.xml中进行配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts>
<package name="shop" extends="struts-default" namespace="/" >
<global-results>
<result name="msg">/WEB-INF/jsp/msg.jsp</result>
</global-results>
<!-- 配置首页访问的Action -->
<action name="index" class="indexAction">
<result name="index">/WEB-INF/jsp/index.jsp</result>
</action> <!-- 配置跳转到注册页面的action -->
<action name="user_*" class="userAction" method="{1}">
<result name="registPage">/WEB-INF/jsp/regist.jsp</result>
<result name="input">/WEB-INF/jsp/regist.jsp</result>
<result name="loginPage">/WEB-INF/jsp/login.jsp</result>
<result name="login">/WEB-INF/jsp/login.jsp</result>
<!-- 登陆成功,重定向到index这个action,这个action再跳转到首页 -->
<result name="loginSuccess" type="redirectAction">index</result>
<!-- 退出登陆成功,重定向到index这个action,这个action再跳转到首页 -->
<result name="quit" type="redirectAction">index</result>
<!-- 验证码输入错误,重新跳转到注册页面 -->
<result name="checkcodeError">/WEB-INF/jsp/regist.jsp</result>
</action> <action name="checkImg" class="checkImg"></action> <!-- 商品模块的Action -->
<action name="product_*" class="productAction" method="{1}">
<result name="findByPid">/WEB-INF/jsp/product.jsp</result>
<result name="findByCid">/WEB-INF/jsp/productList.jsp</result>
<result name="findByCsid">/WEB-INF/jsp/productList.jsp</result>
</action> <!-- 购物车的Action -->
<action name="cart_*" class="cartAction" method="{1}">
<result name="addCart">/WEB-INF/jsp/cart.jsp</result>
<result name="clearCart">/WEB-INF/jsp/cart.jsp</result>
<result name="removeCart">/WEB-INF/jsp/cart.jsp</result>
<result name="myCart">/WEB-INF/jsp/cart.jsp</result>
</action>
</package> </struts>
接下来实现

点击上面的清空购物车的功能
调用的是cart.jsp中的
<a href="${ pageContext.request.contextPath }/cart_clearCart.action" id="clear" class="clear">清空购物车</a>
点击上面途中的删除,调用的是cart.jsp中的
<a href="${ pageContext.request.contextPath }/cart_removeCart.action?pid=<s:property value="#cartItem.product.pid"/>" class="delete">删除</a>
在上面的action中已经做了详细的处理
SSH网上商城四的更多相关文章
- SSH网上商城---使用ajax完成用户名是否存在异步校验
		
小伙伴在上网的时候,需要下载或者观看某些视频资料,更或者是在逛淘宝的时候,我们都需要注册一个用户,当我们填写好各种信息,点击确定的时候,提示用户名已经存在,小编就想,为什么当我们填写完用户名的时候,她 ...
 - SSH网上商城---需求分析+表关系分析
		
SSH---小编初次接触的时候傻傻的以为这个跟SHE有什么关系呢?又是哪路明星歌手,后来才知道小编又土鳖了,原来SSH是这个样子滴,百度百科对她这样阐述,SSH即 Spring + Struts +H ...
 - SSH网上商城一
		
Java高级项目之SSH网上商城项目实战: 1.采用目前最主流的三大框架开发即Struts2+Spring+Hibernate框架整合开发.2.通过AJAX技术提供良好的用户体验.3.提供了邮箱激活的 ...
 - SSH网上商城---用户激活
		
在前面的博客中,小编主要结合SSH网上商城这个项目,简单的介绍了如何实现邮件发送的这个功能,邮件发送了,接下来就是激活了,为什么呢?现在大多网站都要通过对账号进行激活,然后才能注册成功,这是防止恶性注 ...
 - SSH网上商城---邮件发送
		
注册网站账号的时候,都需要发送激活邮件,然后让注册的用户点击激活链接方可完成注册,不过话说回来,为什么注册的时候需要发送邮件呢?为什么不注册的时候直接激活呢?一定要收一封激活帐号的邮件?网站这样做的好 ...
 - 《SSH网上商城》-视频目录--代码可以跑起来
		
本课程是2015年2月份的,就是14年底的. 课程第一天的代码-添加 jsp-api.jar servlet-api.jar就可以跑起来,环境 JDK1.7 和tomcat8, SSH网上商城\S ...
 - [Java]ssh网上商城总结                                                                                                         标签:               hibernatessh                                            2016-05-15 21:03             1099人阅读              评论(32)
		
前几日敲完了ssh网上商城,虽然现在已经敲完了整个系统,却发现自己对于ssh,了解的一点都不多,什么是struts2,什么是spring,什么是hibernate,自己都是稀里糊涂,然后看了一下后面的 ...
 - 【SSH网上商城项目实战01】整合Struts2、Hibernate4.3和Spring4.2
		
转自:https://blog.csdn.net/eson_15/article/details/51277324 今天开始做一个网上商城的项目,首先从搭建环境开始,一步步整合S2SH.这篇博文主要总 ...
 - SSH网上商城---商品详情页的制作
		
在前面的博文中,小编分别简单的介绍了邮件的发送以及邮件的激活,逛淘宝的小伙伴都有这样的体会,比如在搜索框中输入连衣裙这个商品的时候,会出现多种多样各种款式的连衣裙,连衣裙的信息包括价格,多少人购买,商 ...
 
随机推荐
- java方式实现归并排序
			
一.基本思想 归并排序是建立在归并操作上的一种排序算法,该算法是采用分治法的一个典型应用.具体操作如下:所谓的分治就是分而治之,以一分为二的原则,先把序列平均分解成二个左右子序列,然后递归左右二个子序 ...
 - Jmeter(五) - 从入门到精通 - 创建网络计划实战和创建高级Web测试计划(详解教程)
			
1.简介 上一篇中宏哥已经将其的理论知识介绍了一下,这一篇宏哥就带着大家一步一步的把上一篇介绍的理论知识实践一下,然后再说一下如何创建高级web测试计划. 2.网络计划实战 通过上一篇的学习,宏哥将其 ...
 - Codeforces Round #646 (Div. 2)【C. Game On Leaves 题解】
			
题意分析 关于这道题,意思就是两个人摘叶子,谁最后摘到编号为x的谁就赢了.既然是叶子,说明其最多只有一个分支,由于题目上说了是无向图,那就是度数小于等于的节点.也就是一步步移除度数小于等于的节点,直到 ...
 - jQuery-显示与隐藏
			
1.显示与隐藏 show([speed,easing,function]) speed:毫秒单位的时间值 hide([speed,easing,function]) 用法:元素.show()/元素.h ...
 - JavaScript 引用数据类型
			
目录 1. 问题描述 2. 原因分析 3. React 中的引用数据类型 4. 业务场景 5. 参考资料 1. 问题描述 今天在写一个代码题时候, 有一个BUG 导致自己停滞好久, 该BUG 可以描述 ...
 - 手写 new
			
/* 基于内置的 new 关键词,我们可以创建 Dog 的一个实例 zhangsan ,实例可以调用原型上的属性和方法 需求:自己实现一个 _new 方法,也可以模拟出内置 new 后的结果 */ / ...
 - JDBC化繁为简
			
众所周知,jdbc可谓是java连接数据库最基本的方法,通过DriverManager拿到connection,再从connection拿到statement,再从statement中进一步操作得到结 ...
 - Java实现 LeetCode 315 计算右侧小于当前元素的个数
			
315. 计算右侧小于当前元素的个数 给定一个整数数组 nums,按要求返回一个新数组 counts.数组 counts 有该性质: counts[i] 的值是 nums[i] 右侧小于 nums[i ...
 - Java实现 蓝桥杯VIP 算法提高 夺宝奇兵
			
算法提高 夺宝奇兵 时间限制:1.0s 内存限制:512.0MB [题目描述] 在一座山上,有很多很多珠宝,它们散落在山底通往山顶的每条道路上,不同道路上的珠宝的数目也各不相同.下图为一张藏宝地图: ...
 - 运用Navicat for MySQL进行MSSQL数据转移MYSQL
			
当前不同数据库进行数据转移已经不是一件麻烦事情,特别是有很多很方便的工具,而最近我在搜集各种数据时候,也需要进行大量的数据转移,并且数据库和所转移的数据库表都不同,这次给大家介绍个最简单的方法,就是使 ...