发布时间:2023-04-26 文章分类:WEB开发, 电脑百科 投稿人:李佳 字号: 默认 | | 超大 打印

一、新建项目、实体类、servlet

1.新建Dynamic Web project,新建过程如下;
使用Session和cookie会话对象实现简单购物车功能(超详细)
2.在src目录下新建两个包,一个命名为entity,一个命名为servlet,新建过程如下;
使用Session和cookie会话对象实现简单购物车功能(超详细)
3.在entity目录下新建两个实体类,一个名为Cake,一个名为CakeDB,新建过程如下:使用Session和cookie会话对象实现简单购物车功能(超详细)
4.在servlet目录下新建三个servlet,命名分别为ListCakeServlet、PurchaseServlet和CartServlet,新建过程如下:
使用Session和cookie会话对象实现简单购物车功能(超详细)
所有东西建完后结果如图:
使用Session和cookie会话对象实现简单购物车功能(超详细)

二:源代码

1.Cake实体类:

package entity;
public class Cake {
	private String id;
	private String name;
	public Cake() {
	}
	public Cake(String id, String name) {
		this.id = id;
		this.name = name;
	}
	public void setId(String id) {
		this.id=id;
	}
	public String getId() {
		return id;
	}
	public void setName(String name) {
		this.name=name;
	}
	public String getName() {
		return name;
	}
}

2.CakeDB实体类:

package entity;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
public class CakeDB {
	private static Map<String, Cake> cake = new LinkedHashMap<String, Cake>();
    static {//模拟数据库中的记录
        cake.put("1001", new Cake("1001", "A类:巧克力蛋糕"));
        cake.put("1002", new Cake("1002", "B类:水果沙拉蛋糕"));
        cake.put("1003", new Cake("1003", "C类:慕斯蛋糕"));
        cake.put("1004", new Cake("1004", "D类:奶油蛋糕"));
        cake.put("1005", new Cake("1005", "E类:干果蛋糕"));
    }
    // 获得所有的蛋糕
    public static Collection<Cake> getAll() {
        return cake.values();
    }
    // 根据指定的id获蛋糕
    public static Cake getCake(String id) {
        return cake.get(id);
    }
}

3.ListCakeServlet:

package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entity.Cake;
import entity.CakeDB;
@WebServlet("/ListCakeServlet")
public class ListCakeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public ListCakeServlet() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse resp) 
			throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Collection<Cake> cakes = CakeDB.getAll();
        out.write("本站提供的蛋糕有:<br>");
        for (Cake cake : cakes) {
            String url = "PurchaseServlet?id=" + cake.getId();
            out.write(cake.getName() + "<a href='" + url
                    + "'>点击购买</a><br>");
        }
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

4.PurchaseServlet:

package servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import entity.Cake;
import entity.CakeDB;
@WebServlet("/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public PurchaseServlet() {
        super();
    }
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		// 获得用户购买的商品
        String id = req.getParameter("id");
        if (id == null) {
            // 如果id为null,重定向到ListBookServlet页面
            String url = "ListBookServlet";
            resp.sendRedirect(url);
            return;
        }
        Cake book = CakeDB.getCake(id);
        // 创建或者获得用户的Session对象
        HttpSession session = req.getSession();
        // 从Session对象中获得用户的购物车
        List<Cake> cart = (List) session.getAttribute("cart");
        if (cart == null) {
            // 首次购买,为用户创建一个购物车(List集合模拟购物车)
            cart = new ArrayList<Cake>();
            // 将购物城存入Session对象
            session.setAttribute("cart", cart);
        }
        // 将商品放入购物车
        cart.add(book);
        // 创建Cookie存放Session的标识号
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60 * 30);
        cookie.setPath("/Servlet");
        resp.addCookie(cookie);
        // 重定向到购物车页面
        String url = "CartServlet";
        resp.sendRedirect(url);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doGet(request, response);
	}
}

5.CartServlet:

package servlet;
import entity.Cake;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {
    protected void  doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        List<Cake> cart = null;
        boolean purFlag = true;
        HttpSession session = req.getSession(false);
        if (session == null)
        {
            purFlag =false;
        }
        else {
            cart = (List) session.getAttribute("cart");
            if (cart == null){
                purFlag=false;
            }
        }
        if(!purFlag){
            out.write("抱歉,您还没有购买任何商品!<br>");
        }
        else {
            out.write("您购买的蛋糕有:<br>");
            double price = 0;
            for (Cake cake:cart){
                out.write(cake.getName() +"<br>");
            }
        }
    }
}

三、运行

1.在ListCakeServlet文件下运行,点击鼠标右键,选择run as,具体如图:
使用Session和cookie会话对象实现简单购物车功能(超详细)
2.运行结果如图:
使用Session和cookie会话对象实现简单购物车功能(超详细)
点击购买之后跳转CartServlet页面,比如我点了巧克力蛋糕后:

使用Session和cookie会话对象实现简单购物车功能(超详细)
以上就是使用Session和cookie会话对象实现简单购物车功能。希望对你有帮助哦~