javaweb学习——session和Cookie实现购物车功能

1.创建Book类,实现对图书信息的封装。

package cn.it.sessionDemo.example1;

import java.io.Serializable;

/**
 * 该类实现对图书的封装
 * 
 * @author 12428
 *
 */
public class Book implements Serializable {
    private static final long serialVersionUID = 1L;
    private String ID;
    private String name;

    public Book() {

    }

    public Book(String ID, String name) {
        this.ID = ID;
        this.name = name;
    }

    public String getID() {
        return ID;
    }

    public void setID(String iD) {
        ID = iD;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2.创建一个BookDB类实现对图书类的操作

package cn.it.sessionDemo.example1;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 该类实现数据库模拟
 * 
 * @author 12428
 *
 */
public class BookDB {
    private static Map books = new LinkedHashMap();
    // 静态代码块在Java类被加载时执行,由于类只加载一次,应此静态代码块只执行一次。
    static {
        books.put("1", new Book("1", "javaweb开发"));
        books.put("2", new Book("2", "jdbc开发"));
        books.put("3", new Book("3", "java基础"));
        books.put("4", new Book("4", "struts开发"));
        books.put("5", new Book("5", "spring开发"));
    }

    // 获得所有的图书
    public static Collection getAll() {
        return books.values();
    }

    // 根据指定的ID获得图书
    public static Book getBook(String ID) {
        return books.get(ID);
    }

}

3.创建一个ListBookServlet类,用来显示可购买的图书信息。

package cn.it.sessionDemo.example1;

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;

/**
 * 该servlet是显示所有的图书列表。通过图书后面的购买连接可以把图书添加到购物车中
 * 
 * @author 12428
 *
 */
@WebServlet("/ListBookServlet")
public class ListBookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ListBookServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Collection books = BookDB.getAll();
        out.write("本站的图书有:");
        for (Book b : books) {
            // 将图书的id值作为参数传过去
            String url = "/SessionDemo2/PurchaseServlet?id=" + b.getID();
            out.write(b.getName() + "点击购买
"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

4.创建一个实现购物车功能的servlet类

package cn.it.sessionDemo.example1;

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;

/**
 * 该servlet类是用于实现购物车功能,既将用户购买的东西作为session的属性值存进去,再重定向到 到已购买商品的也买你
 * 
 * @author 12428
 *
 */
@WebServlet("/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public PurchaseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获得用户的购买信息
        String id = request.getParameter("id");
        // 有些用户会直接访问这个Servlet,先判断访问时是否带有书的ID
        if (id == null) {
            // 如果Id为空,返回图书列表Servlet
            String url = "/SessionDemo2/ListBookServlet";
            response.sendRedirect(url);
//此处一定要返回,不然会出现错误
return; } // 获取购买的图书信息 Book book = BookDB.getBook(id); // 创建session对象 HttpSession session = request.getSession(); // 从session中获得购物车对象 List cart = (List) session.getAttribute("cart"); // 判断session对象是否有cart这个属性,如果没有这个属性的话,集合cart的值应为空 if (cart == null) { // 没有cart属性,用户是首次购买,为用户创建一个购物车 cart = new ArrayList(); // 将购物车对象添加到session对象中 session.setAttribute("cart", cart); } // 将商品放入购物车 cart.add(book); // 创建一个Cookie存放session的信息 Cookie cookie = new Cookie("JSESSION", session.getId()); cookie.setMaxAge(60 * 30); cookie.setPath("/SessionDemo2"); // 将cookie发送到客户端 response.addCookie(cookie); // 重定向到已购买商品的页面。 String url = "/SessionDemo2/CartServlet"; response.sendRedirect(url); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

5.创建一个展示用户购买信息的类

package cn.it.sessionDemo.example1;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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;

@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public CartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        // 变量cart引用用户的购物车
        List cart = null;
        // 创建一个变量是来判断用户是否购买过商品
        boolean Flag = true;
        // 获得用户的session,如果没有查到也不创建新的session。
        HttpSession session = request.getSession(false);
        // 如果session为空,Flag为false;
        if (session == null) {
            Flag = false;
        } else {// 不为空,就获得用户的购物车
            cart = (List) session.getAttribute("cart");
            // 如果用户的购物车为空,就设置Falg为false。
            if (cart == null) {
                Flag = false;
            }

        }

        // 如果Flag为false,表明用户没有购买过商品,重定向到ListServlet页面。
        if (!Flag) {
            out.write("对不起,你没有购买任何商品");
        } else {
            // 显示用户的购买信息
            out.write("你购买的商品有:");
            for (Book b : cart) {
                out.write(b.getName() + "
"); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

 

转载于:https://www.cnblogs.com/zhilili/p/10874754.html

你可能感兴趣的:(javaweb学习——session和Cookie实现购物车功能)