Session 购物车

Session 购物车_第1张图片

在jsp页面导包【Alt+/】

product_list.jsp

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




Insert title here


	

Iphone7


小米6


三星Note8


魅族7


华为9


CarServlet.java

package com.zhujunwei;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/html;charset=utf-8");
		//1、获取要添加到购物车的商品id
		int id = Integer.parseInt(request.getParameter("id"));
		String[] names = {"Iphone7","小米6","魅族7","华为9"};
		String name = names[id];
		
		//2、获取购物车存放东西的session Map Iphone7 3
		//把一个map对象村方法到session里面去,并且保证只存放一次。
		@SuppressWarnings("unchecked")
		Map map = (Map) request.getSession().getAttribute("cart");
		//session里面没有存放任何东西
		if(map ==null)
		{
			map = new LinkedHashMap();
			request.getSession().setAttribute("cart", map);
		}
		//3、判断购物车里面有没有该商品
		if(map.containsKey(name))
		{
			//在原来的值的基础上+1
			map.put(name, map.get(name)+1);
		}else {
			//没有购买过该商品,当前数量为1
			map.put(name, 1);
		}
		
		//4.输出界面
		response.getWriter().write("

继续购物


"); response.getWriter().write("

购物车结算


"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

Cart.jsp

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




Insert title here


	

您的购物车的商品如下:

<% //1、先获取到map Map map = (Map)session.getAttribute("cart"); //2、遍历map if(map!=null){ for(String key : map.keySet()){ int value = map.get(key); %>

名称:<%=key %> 数量:<%=value %>

<% } } %> 清空购物车

ClearCartServlet.java

package com.zhujunwei;

import java.io.IOException;
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("/ClearCartServlet")
public class ClearCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("cart");
		response.sendRedirect("cart.jsp");
	}

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

}

你可能感兴趣的:(Java,Web,HTML5,购物车,Session)