(重點)JavaWeb(入門篇12)Session的簡單實現購物車

一、Session的簡單實現購物車

1.實現功能

根據Session ID 作爲標識的功能,實現添加購物車的功能(數據儲存在Session不使用數據庫),

  • 商品展示頁展示商品,(ShowGoods)
  • 商品添加頁可以是展示頁提交表單後效果展示(AddGoods )
  • 購物車頁展示你添加的所有的購物信息(Cart)
    在這裏插入圖片描述
    加入購物車(這裏可以使用post去掉過長的url)
    在這裏插入圖片描述
    購物車
    在這裏插入圖片描述
    繼續購買
    在這裏插入圖片描述

在這裏插入圖片描述
購物車
在這裏插入圖片描述
清理購物車
在這裏插入圖片描述

2. 核心代碼

1.根據session設置Attribute屬性

req.getSession().setAttribute("sessionGoods", new HashMap<String, Integer>());

2.根據session獲得Attribute的值

HashMap<String, Integer> map = (HashMap<String, Integer>) req.getSession().getAttribute("sessionGoods");

3.寫入鏈接a標籤實現對映射的訪問

 out.write("<a href='./ShowGoods'><h1>繼續購買</h1></a>");

3.框架

在這裏插入圖片描述

4.代碼

1.展示頁面ShowGoods
(1)ShowGoods展示頁面Servlet

package com.bmft.session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用戶首先向用戶展示商品的類,
 * 使用轉發或者重定向到一個showGoods.jsp
 */
public class ShowGoods extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("showGoods.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}

(2)展示頁面ShowGoods的 jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>商品展示Show Goods</title>
</head>
<body>
<h1>商品展示Show Goods</h1>
<form action="<%=request.getContextPath()%>/AddGoods" method="get">
    《Java編程思象》<input type="checkbox" name="goods" value="《Java編程思象》"><br>
    《JavaWeb入門到放棄》<input type="checkbox" name="goods" value="《JavaWeb入門到放棄》"><br>
    《Java入土實踐》<input type="checkbox" name="goods" value="《Java入土實踐》"><br>
    <input type="submit" value="加入購物車">
</form>
</body>
</html>

2.添加商品提示頁面AddGoods的Serlet

package com.bmft.session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * 用戶點擊商品後,實現的添加至購物車的邏輯和
 * 返回是否繼續頁面的類
 */

public class AddGoods extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");//設置客戶端的接受方式
        System.out.println("=======AddGoods進入成功=========");

        if (req.getSession().getAttribute("sessionGoods") == null) {
            req.getSession().setAttribute("sessionGoods", new HashMap<String, Integer>());
        }
        HashMap<String, Integer> map = (HashMap<String, Integer>) req.getSession().getAttribute("sessionGoods");

        //1.獲取提交的表單,如何獲得多個數據通過一個關鍵字呢
        //req.getParameterValues
        String[] goods = req.getParameterValues("goods");
        PrintWriter out = resp.getWriter();

        //如果購物的提交的post goods不爲空就,顯示添加成功,並返回是否繼續的
        //或者結算的頁面
        if (goods != null) {
            for (String good : goods) {
                if (map.get(good) == null) {
                    map.put(good, 0);
                }
                map.put(good, map.get(good) + 1);
                out.write("<h3>添加" + good + "成功</h3><br>");
                System.out.println("<h3>添加" + good + "成功</h3><br>");
            }

        } else {
            out.write("<h3>您沒有選擇任何商品哦</h3>");
            System.out.println("<h3>您沒有選擇任何商品哦</h3>");
        }
        out.write("<a href='./ShowGoods'><h1>繼續購買</h1></a>");
        out.write("<a href='./Cart'><h1>購物車</h1></a>");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

3.購物車Cart頁面Servlet

package com.bmft.session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * 購物車展示類
 * 更具用戶session,展示對應是商品
 */
public class Cart extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");//設置客戶端的接受方式
        //清除商品
        if (req.getParameter("isInvalidate") != null && req.getParameter("isInvalidate").equals("true")) {

            req.getSession().setAttribute("sessionGoods", null);
        }
        PrintWriter out = resp.getWriter();
        if (req.getSession().getAttribute("sessionGoods") != null) {
            HashMap<String, Integer> map = (HashMap<String, Integer>) req.getSession().getAttribute("sessionGoods");
            //展示對應是商品
            for (String s : map.keySet()) {
                out.write("<h4>" + s + " 數量 " + map.get(s) + "</h4>");
            }

        } else {
            out.write("<h4>" + "您的購物車空蕩蕩的哦" + "</h4>");
        }
        out.write("<a href='./ShowGoods'><h1>繼續購買</h1></a>");
        out.write("<a href='./Cart?isInvalidate=true'><h1>清除商品</h1></a>");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}


5.頁面展示

  • 只要服務器不關閉並不更換瀏覽器,可以一直儲存session數據,(由於沒有設置手動清除req.getSession().invalidate();,或者web.xml下配置自動清除)
  • 可以嘗試開多個網頁查看效果

6.遇到的問題和解決

1.試圖寫入jsp頁面一個表單實現跳轉-- 失敗

out.write("<%=request.getContextPath()%>/AddGoods")

解決方法:寫入鏈接a並使用./跳轉到更目錄,在訪問映射

out.write("<a href='./ShowGoods'><h1>繼續購買</h1></a>");
out.write("<a href='./Cart'><h1>購物車</h1></a>");

2.直接 獲得map數據導致的空指針異常
解決:判斷如果爲空,就添加一個Attribute("")

if (req.getSession().getAttribute("sessionGoods") == null) {
	req.getSession().setAttribute("sessionGoods", new HashMap<String, Integer>());
}

3.map值(商品)數量空指針異常
如果你直接沒有給,map,put值的話直接使用

map.put(good,map.get(good)+1);

因爲一開map的value值是空,就是 null +1 就是空指針異常
解決:先判斷value是否爲空,如果爲空,就先給初始的value值

for (String good : goods) {
	if (map.get(good)==null){
		map.put(good,0);
	}
	map.put(good, map.get(good)+1);
	out.write("<h3>添加" + good + "成功</h3><br>");
	System.out.println("<h3>添加" + good + "成功</h3><br>");
}

4.清理購物車拋出空指針異常

if(eq.getParameter("isInvalidate").equals("true"))
{
	//清理
}

如果沒有點擊清理,就沒有url累積,沒有Parameter,就會空指針異常
解決:加上空指針判斷


 if (req.getParameter("isInvalidate") != null && req.getParameter("isInvalidate").equals("true")) {
     req.getSession().setAttribute("sessionGoods", null);
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章