通過Cookie實(shí)現(xiàn)購(gòu)物車

通過Cookie實(shí)現(xiàn)購(gòu)物車

在這里小小推薦下我的個(gè)人博客

csdn:雷園的csdn博客

個(gè)人博客:雷園的個(gè)人博客

簡(jiǎn)書:雷園的簡(jiǎn)書

導(dǎo)包:

import com.ambow.springboot.vo.CartVo;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

獲取Cookie


    /**
     * 獲取名為"cart"的cookie
     *
     * @param request
     * @return cookie
     */
    public Cookie getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        Cookie cart_cookie = null;
        for (Cookie cookie : cookies) {
            if ("cart".equals(cookie.getName())) { //獲取購(gòu)物車cookie
                cart_cookie = cookie;
            }
        }
        return cart_cookie;
    }

獲取Cookie中的購(gòu)物車列表


    /**
     * 獲取cookie中的購(gòu)物車列表
     *
     * @param response
     * @param request
     * @return 購(gòu)物車列表
     * @throws UnsupportedEncodingException 拋出異常
     */
    public List<CartVo> getCartInCookie(HttpServletResponse response, HttpServletRequest request) throws
            UnsupportedEncodingException {
        // 定義空的購(gòu)物車列表
        List<CartVo> items = new ArrayList<CartVo>();
        String value_1st = "";
        // 購(gòu)物cookie
        Cookie cart_cookie = getCookie(request);
        // 判斷cookie是否為空
        if (cart_cookie != null) {
            // 獲取cookie中String類型的value
            value_1st = URLDecoder.decode(cart_cookie.getValue(), "utf-8");//從cookie獲取購(gòu)物車
            // 判斷value是否為空或者""字符串
            if (value_1st != null && !"".equals(value_1st)) {
                // 解析字符串中的數(shù)據(jù)為對(duì)象并封裝至list中返回給上一級(jí)
                String[] arr_1st = value_1st.split("==");
                for (String value_2st : arr_1st) {
                    String[] arr_2st = value_2st.split("=");
                    CartVo item = new CartVo();
                    item.setGoodsId(Integer.parseInt(arr_2st[0])); //商品id
                    item.setGoodsTypeId(Integer.parseInt(arr_2st[1])); //商品類型ID
                    item.setGoodsName(arr_2st[2]); //商品名
                    item.setGoodsPrice(Integer.parseInt(arr_2st[3])); //商品市場(chǎng)價(jià)格
                    item.setGoodsDiscount(Integer.parseInt(arr_2st[4]));//商品折后價(jià)格
                    item.setGoodsNum(Integer.parseInt(arr_2st[5]));//商品月銷量
                    item.setGoodsInfo(arr_2st[6]);//商品詳情
                    item.setNum(Integer.parseInt(arr_2st[7]));//加入購(gòu)物車數(shù)量
                    items.add(item);
                }
            }
        }
        return items;

    }

制作cookie所需value


    /**
     * 制作cookie所需value
     *
     * @param cartVos 購(gòu)物車列表
     * @return 解析為字符串的購(gòu)物車列表,屬性間使用"="相隔,對(duì)象間使用"=="相隔
     */
    public String makeCookieValue(List<CartVo> cartVos) {
        StringBuffer buffer_2st = new StringBuffer();
        for (CartVo item : cartVos) {
            buffer_2st.append(item.getGoodsId() + "=" + item.getGoodsTypeId() + "=" + item.getGoodsName() + "="
                    + item.getGoodsPrice() + "=" + item.getGoodsDiscount() + "=" + item.getGoodsNum() + "=" + item
                    .getGoodsInfo() + "=" + item.getNum() + "==");
        }
        return buffer_2st.toString().substring(0, buffer_2st.toString().length() - 2);
    }

添加,刪除,清空購(gòu)物車方法


    /**
     * 根據(jù)ID刪除刪除購(gòu)物車內(nèi)的商品
     *
     * @param goodsId  商品ID
     * @param request
     * @param response
     * @return 成功與否
     * @throws UnsupportedEncodingException 拋出異常
     */
    @RequestMapping("/deleteByGoodsId/{goodsId}")
    public String deleteByGoodsId(@PathVariable("goodsId") Integer goodsId, HttpServletRequest request,
                                  HttpServletResponse response) throws UnsupportedEncodingException {
        // 獲取cookie中購(gòu)物車列表
        List<CartVo> cartVos = getCartInCookie(response, request);
        CartVo deleteCart = null;
        // 判斷購(gòu)物車列表是否為空
        if (cartVos.size() > 0) {
            // 循環(huán)購(gòu)物車列表尋找相同ID的商品
            for (CartVo c : cartVos) {
                if (c.getGoodsId().equals(goodsId)) {
                    deleteCart = c;
                    break;
                }
            }
            // 判斷是否找到相同ID的商品
            if (deleteCart != null) {
                // 判斷購(gòu)物車中商品的數(shù)量
                if (deleteCart.getNum() > 1) {
                    // 數(shù)量大于1增讓數(shù)量-1
                    deleteCart.setNum(deleteCart.getNum() - 1);
                    cartVos.remove(deleteCart);
                    cartVos.add(deleteCart);
                } else {
                    // 否則直接刪除該商品在購(gòu)物車中的信息
                    cartVos.remove(deleteCart);
                }
                // 獲取名為"cart"的cookie
                Cookie cookie = getCookie(request);
                // 為cookie設(shè)置value
                cookie.setValue(URLEncoder.encode(makeCookieValue(cartVos), "utf-8"));
                // 設(shè)置壽命
                cookie.setMaxAge(60 * 10);
                // 設(shè)置路徑
                cookie.setPath("/");
                // 更新cookie
                response.addCookie(cookie);
            }
        }
        return "success";
    }

    /**
     * 清空購(gòu)物車
     *
     * @param response
     * @param request
     * @return 成功與否
     */
    @RequestMapping("/deleteAllCookie")
    public String deleteCookie(HttpServletResponse response, HttpServletRequest request) {
        // 獲取名為"cart"的cookie
        Cookie cookie = getCookie(request);
        // 設(shè)置壽命為0秒
        cookie.setMaxAge(0);
        // 設(shè)置路徑
        cookie.setPath("/");
        // 設(shè)置cookie的value為null
        cookie.setValue(null);
        // 更新cookie
        response.addCookie(cookie);
        return "success";
    }

    /**
     * 獲取購(gòu)物車列表
     *
     * @param request
     * @param response
     * @return 購(gòu)物車列表
     * @throws UnsupportedEncodingException 拋出異常
     */
    @RequestMapping("/getCart")
    public List<CartVo> getCart(HttpServletRequest request, HttpServletResponse response) throws
            UnsupportedEncodingException {
        return getCartInCookie(response, request);
    }

    /**
     * 添加商品至購(gòu)物車列表
     *
     * @param goodsId  商品ID
     * @param request
     * @param response
     * @throws UnsupportedEncodingException 異常拋出
     */
    @RequestMapping("/addGoodsToCart/{goodsId}")
    public void addGoodsToCart(@PathVariable("goodsId") Integer goodsId, HttpServletRequest request,
                               HttpServletResponse response) throws UnsupportedEncodingException {
        // 從cookie中獲取購(gòu)物車列表
        List<CartVo> cartVos = getCartInCookie(response, request);
        Cookie cookie_2st;
        // 如果購(gòu)物車列表為空
        if (cartVos.size() <= 0) {
            //TODO 根據(jù)商品ID獲取商品信息
            CartVo cartVo = new CartVo(); // 測(cè)試用,實(shí)際應(yīng)當(dāng)根據(jù)id獲取
            cartVo.setNum(1);
            cartVo.setGoodsId(1);
            cartVo.setGoodsNum(1);
            cartVo.setGoodsTypeId(1);
            cartVo.setGoodsPrice(1);
            cartVo.setGoodsDiscount(1);
            cartVo.setGoodsName("雷園");
            // 將當(dāng)前傳來的商品添加到購(gòu)物車列表
            cartVos.add(cartVo);
            if (getCookie(request) == null) {
                // 制作購(gòu)物車cookie數(shù)據(jù)
                cookie_2st = new Cookie("cart", URLEncoder.encode(makeCookieValue(cartVos), "utf-8"));
                cookie_2st.setPath("/");//設(shè)置在該項(xiàng)目下都可以訪問該cookie
                cookie_2st.setMaxAge(60 * 30);//設(shè)置cookie有效時(shí)間為30分鐘
                response.addCookie(cookie_2st);//添加cookie
            } else {
                cookie_2st = getCookie(request);
                cookie_2st.setPath("/");//設(shè)置在該項(xiàng)目下都可以訪問該cookie
                cookie_2st.setMaxAge(60 * 30);//設(shè)置cookie有效時(shí)間為30分鐘
                cookie_2st.setValue(URLEncoder.encode(makeCookieValue(cartVos)));
                response.addCookie(cookie_2st);//添加cookie
            }
        }
        // 當(dāng)獲取的購(gòu)物車列表不為空時(shí)
        else {
            int bj = 0;
            for (CartVo cart : cartVos) {
                // 如果購(gòu)物車中存在該商品則數(shù)量+1
                if (cart.getGoodsId() == goodsId) {
                    cart.setNum(cart.getNum() + 1);
                    bj = 1;
                    break;
                }
            }
            if (bj == 0) {
                //TODO 根據(jù)商品ID獲取商品信息
                CartVo cartVo = new CartVo(); // 測(cè)試用,實(shí)際應(yīng)當(dāng)根據(jù)id獲取
                cartVo.setNum(1);
                cartVo.setGoodsId(goodsId);
                cartVo.setGoodsNum(1);
                cartVo.setGoodsTypeId(1);
                cartVo.setGoodsPrice(1);
                cartVo.setGoodsDiscount(1);
                cartVo.setGoodsName("雷園");
                // 將當(dāng)前傳來的商品添加到購(gòu)物車列表
                cartVos.add(cartVo);
            }
            // 獲取名為"cart"的cookie
            cookie_2st = getCookie(request);
            cookie_2st.setPath("/");//設(shè)置在該項(xiàng)目下都可以訪問該cookie
            cookie_2st.setMaxAge(60 * 30);//設(shè)置cookie有效時(shí)間為30分鐘
            cookie_2st.setValue(URLEncoder.encode(makeCookieValue(cartVos))); // 設(shè)置value
            response.addCookie(cookie_2st);//添加cookie
        }
    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容