(重点)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);
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章