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="image
___________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;  0px; height: 0px; position: absolute; border- 1px;" class="zoomPup"></div><div style="position: absolute; z-index: 5001; left: 312px; top: 0px; display: block;" class="zoomWindow"><div style=" 368px;" class="zoomWrapper"><div style=" 100%; position: absolute; display: none;" class="zoomWrapperTitle"></div><div style=" 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="image
___________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中已经做了详细的处理

原文地址:https://www.cnblogs.com/kebibuluan/p/8335298.html