session实现购物车

功能:应用会话技术实现购物车功能,点击货物,将货物保存至购物车,实现购物车的增添清空功能


主界面代码:

<%@ page contentType="text/html;charset=UTF-8" language="java"  pageEncoding="UTF-8" %>
<%@page import="java.util.Map" %>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    Product List


Product List

//购物车界面跳转链接 ">View Cart

<% //获取所有商品 Map products = (Map)request.getAttribute("products"); for(int id : products.keySet()) { %> <%-- 将商品一一显示出来,并且在点击的时候将商品ID添加到购物车中,并访问购物车--%> "><%= products.get(id) %>
<% } %>


查看购物车界面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="java.util.Map" %>
<%-- 导入标签 --%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    View Cart


View Cart

">Product List

">Empty Cart

<% //获取session中的两个对象 Map products = (Map)request.getAttribute("products"); Map cart = (Map)request.getSession().getAttribute("cart"); if (cart == null || cart.size() == 0){ //如果购物车中没有东西 out.println("Your cart is empty."); }else { for (int id: cart.keySet()){ //输出购物车列表 out.println(products.get(id) + "(qty:" + cart.get(id) +")
"); } } %>


主servlet代码:

import com.sun.deploy.net.HttpRequest;
import com.sun.deploy.net.HttpResponse;

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 javax.xml.ws.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class StoreServlet extends HttpServlet {

    private final Map products = new HashMap<>();

    public StoreServlet(){      //在商品库中添加商品
        this.products.put(1,"Sandpaper");
        this.products.put(2,"Nails");
        this.products.put(3,"Glue");
        this.products.put(4,"Paint");
        this.products.put(5,"Tape");

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");    //获取jsp页面传来的action参数的值
        if(action == null){
            action = "browse";     //如果值为空,赋值browse,将页面定向至主界面
        }

        switch (action){
            case "addToCart":
                this.addToCart(request,response);
                break;
            case "viewCart":
                this.viewCart(request,response);
                break;
            case "browser":
                this.browse(request,response);
                break;
            case "emptyCart":
                this.emptyCart(request,response);
                break;
            default:
                this.browse(request,response);
                break;
        }
    }

    //购物车界面
    private void viewCart(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
        request.setAttribute("products",this.products);
        request.getRequestDispatcher("/jsp/view/viewCart.jsp")
                .forward(request,response);    //页面重定向至购物车页面
    }

    //主界面
    private void browse(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
        request.setAttribute("products",this.products);
        request.getRequestDispatcher("/jsp/view/browse.jsp")
                .forward(request,response);
    }

    //添加商品到购物车
    private void addToCart(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        int productId;
        try {
            //获取选择的商品ID
            productId = Integer.parseInt(request.getParameter("productId"));
        }catch (Exception e){
            response.sendRedirect("shop");
            return;
        }

        HttpSession session = request.getSession();
        if(session.getAttribute("cart") == null){
            //获取购物车session,如果不存在重新添加。
            session.setAttribute("cart",new Hashtable());
        }

        @SuppressWarnings("unchecked")

        Map  cart = (Map)session.getAttribute("cart");
        if(!cart.containsKey(productId)){
            //如果列表中不包含该ID,将该ID添加到购物车中,并显示选择商品数为0
            cart.put(productId,0);
        }
        //将选择的商品数量+1
        cart.put(productId,cart.get(productId) + 1);
        response.sendRedirect("shop?action=viewCart");     //跳转至购物车界面

    }

    //清空购物车
    private void emptyCart(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
        request.getSession().removeAttribute("cart");
        response.sendRedirect("shop?action = viewCart");
    }
}


配置文档:




    
        StoreServlet
        com.wrox.StoreServlet
    
    
        StoreServlet
        /shop
    


实现结果:

session实现购物车_第1张图片

session实现购物车_第2张图片

你可能感兴趣的:(Java,Web)