1. 程式人生 > >淘淘商城27_購物車_01新增購物車和將購物車儲存到cookie

淘淘商城27_購物車_01新增購物車和將購物車儲存到cookie

一、需求分析

購物車大概分兩種:京東樣式的和淘寶樣式的

京東:在使用者不用登入的情況下也可以將商品放入到購物車

淘寶:使用者必須登入成功後才能將商品放入到購物車

 

我們要做的類似京東:購物車在使用者不登陸的情況下也可以使用購物車。需要把購物車的商品資訊寫入cookie中。所有對購物車的操作都是操作cookie。有效的降低資料庫的壓力。

缺點:換一臺電腦後購物車的商品不能同步。

 

1、購物車是一個獨立的表現層工程。

2、新增購物車不要求登入。可以指定購買商品的數量。

3、展示購物車列表頁面

4、修改購物車商品數量

5、刪除購物車商品

二、新增購物車

1. 流程

在商品詳情頁面點選“加入購物車”按鈕提交一個請求把商品id傳遞給Controller,Controller接收id,Controller呼叫Service根據商品id查詢商品基本資訊。把商品寫入cookie中,加入cookie之前先從cookie中把購物車的商品取出來判斷當前購物車商品列表中是否有此商品,如果有數量加一,如果沒有新增一個商品,數量為1。展示給使用者購物車列表。

2. 建立taotao-cart-web工程

2.1 pom.xml檔案

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.taotao</groupId>
    <artifactId>taotao-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>taotao-cart-web</artifactId>
  <packaging>war</packaging>
  
  <dependencies>
     	
		<dependency>
			<groupId>com.taotao</groupId>
			<artifactId>taotao-common</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
		<dependency>
  			<groupId>com.taotao</groupId>
		    <artifactId>taotao-manager-interface</artifactId>
		    <version>0.0.1-SNAPSHOT</version>
  		</dependency>
  		
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jms</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
		<!-- JSP相關 -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jsp-api</artifactId>
			<scope>provided</scope>
		</dependency>

		<!-- dubbo相關 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo</artifactId>
			<exclusions>
				<exclusion>
					<artifactId>spring</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
				<exclusion>
					<artifactId>netty</artifactId>
					<groupId>org.jboss.netty</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
		</dependency>
		<dependency>
			<groupId>com.github.sgroschupf</groupId>
			<artifactId>zkclient</artifactId>
		</dependency>
		
		<!-- httpclient -->
			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpclient</artifactId>
			</dependency>
			
			<!-- 單元測試 -->
			<dependency>
				<groupId>junit</groupId>
				<artifactId>junit</artifactId>
				<scope>test</scope>
			</dependency>
	</dependencies>
	
	
	<build>
		<!-- 配置外掛 -->
		<plugins>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<configuration>
					<port>8089</port>
					<path>/</path>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

2.2 配置檔案

2.2.1 spingmvc.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
      	http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
	<!-- 配置註解驅動 -->
	<mvc:annotation-driven />
	<!-- 檢視解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	<!-- 配置包掃描器,掃描@Controller註解的類 -->
	<context:component-scan base-package="com.taotao.cart.controller"/>
	<!-- 配置靜態資源 -->
	<mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
	<mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
	
	<!-- 引用dubbo服務 -->
	<dubbo:application name="taotao-cart"/>
	<dubbo:registry protocol="zookeeper" address="172.18.34.94:2181"/>
	<!-- 釋出dubbo服務 -->
	<!-- <dubbo:reference interface="com.taotao.content.service.ItemCatService"  id="itemCatService""  timeout = "300000" /> -->
</beans>      

參考taotao-portal工程 

2.2.2 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>taotao-cart-web</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
    <servlet-name>taotao-cart-web</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>taotao-cart-web</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>taotao-cart-web</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

3. 新增購物車的功能

4. controller層CartController.java

4.1 邏輯:

  1.從cookie中取出商品資訊,購物車中的商品資訊儲存在cookie中

  2.判斷選擇的商品是否存在於購物車中

  3.若存在,則購物車中商品數量加1

  4.若不存在,則直接新增商品

  5.將購物車儲存到cookie中,設定生命週期,通常是7天,按秒算

  6.返回成功頁面

package com.taotao.cart.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.taotao.pojo.TbItem;
import com.taotao.service.ItemService;
import com.taotao.utils.CookieUtils;
import com.taotao.utils.ExceptionUtil;
import com.taotao.utils.JsonUtils;

@Controller
public class CartController {
	private static final Logger LOGGER = LoggerFactory.getLogger(CartController.class);
	@Autowired
	private ItemService itemService;
	
	@Value("${TT_CART}")
	private String TT_CART;
	@Value("${COOKIE_CART_EXPIRE}")
	private Integer COOKIE_CART_EXPIRE;
	
	/**
	 * 新增商品到購物車
	 * @param itemId
	 * @param num
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/cart/add/{itemId}")
	public String addCart(@PathVariable Long itemId, @RequestParam(defaultValue="1") Integer num, HttpServletRequest request, HttpServletResponse response){
		try {
			//1.從cookie中取出商品資訊,購物車中的商品資訊儲存在cookie中
			List<TbItem> cartList = getCartList(request, response);
			//2.判斷選擇的商品是否存在於購物車中
			boolean flag = false ;
		    for (TbItem tbItem : cartList) {//3.若存在,則購物車中商品數量加1,
		    	//注意封裝類的轉換Long
		    	//由於tbItem的ID與引數中的itemId都是包裝型別的Long,要比較是否相等不要用==,
                // 因為那樣比較的是物件的地址而不是值,為了讓它們比較的是值,那麼可以使用.longValue來獲取值 

				if (tbItem.getId()==itemId.longValue()) {
					tbItem.setNum(tbItem.getNum()+num);
					flag = true;
					break;//跳出迴圈
				} 
			}
		  //4.若不存在,則直接新增商品,
		    if (! flag) {
				//先從tb_item中查詢出商品資訊
		    	TbItem item = itemService.getItemById(itemId);
		    	//圖片
		    	if (item.getImage() !=null) {
		    		String images = item.getImage();
		    		String[] imageArr = images.split(",");
		    		item.setImage(imageArr[0]);
				}
		    	item.setNum(num);//購買數量
		    	cartList.add(item);//將商品新增到購物車
			}
			//5.將購物車儲存到cookie中,設定生命週期,通常是7天,按秒算
		    CookieUtils.setCookie(request, response, TT_CART, JsonUtils.objectToJson(cartList), COOKIE_CART_EXPIRE);
		} catch (Exception e) {
			LOGGER.error("新增購物車失敗", e);
			return "cartError";
		}
		return "cartSuccess";
	}
	
	/**
	 * 從cookie中查詢購物車中商品資訊
	 * cookie中儲存商品的名稱,id,圖片,價格
	 * @param request
	 * @param response
	 * @return
	 */
	private List<TbItem> getCartList(HttpServletRequest request, HttpServletResponse response){
		String jsonData = CookieUtils.getCookieValue(request, TT_CART, true);//取出的是json格式的字串
		if (StringUtils.isNotEmpty(jsonData)) {//不為空,說明cookie中存在資料
			List<TbItem> list = JsonUtils.jsonToList(jsonData, TbItem.class);
			return list;
		}
		return new ArrayList<>();
	}
}

4.2. Dubbo配置

springmvc.xml

applicationContext-service.xml

我們在taotao-manager-service工程中有配置

4.3 resource.properties

#購物車取商品的key
TT_CART=TT_CART
#cookie生命週期,通常是7天,604800秒
COOKIE_CART_EXPIRE=604800

4.4 cartSuccess.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta name="format-detection" content="telephone=no">

<link rel="stylesheet" type="text/css"
	href="/css/base.css">
<link href="/css/initcart.css" type="text/css"
	rel="stylesheet">
<title>商品已成功加入購物車</title>
<style id="style-1-cropbar-clipper">
/* Copyright 2014 Evernote Corporation. All rights reserved. */
.en-markup-crop-options {
	top: 18px !important;
	left: 50% !important;
	margin-left: -100px !important;
	width: 200px !important;
	border: 2px rgba(255, 255, 255, .38) solid !important;
	border-radius: 4px !important;
}

.en-markup-crop-options div div:first-of-type {
	margin-left: 0px !important;
}
</style>
</head>
<body class="root61">

    <jsp:include page="commons/header.jsp" />
	<!--main start-->
	<div class="w main">
		<div class="left">
			<div class="m" id="succeed">

				<div class="corner tl"></div>
				<div class="corner tr"></div>
				<div class="corner bl"></div>
				<div class="corner br"></div>
				<div class="success">
					<div class="success-b">
						<h3>商品已成功加入購物車!</h3>
						<span id="flashBuy" style="display: none">商品數量有限,請您儘快下單並付款!</span>
					</div>
					<span id="initCart_next_go"> <a class="btn-1"
						href="/cart/cart.html"
						id="GotoShoppingCart">去購物車結算</a> <span class="ml10">您還可以 <a
							class="ftx-05" href="javascript:history.back();">繼續購物</a></span>
					</span>
				</div>
			</div>
			<!--succeed end-->

		</div>
	</div>
   <jsp:include page="commons/footer.jsp" />


</body>
</html>

è¿éåå¾çæè¿°