puduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="product?id=0"><h3>Iphone8</h3></a><br/>
<a href="product?id=1"><h3>小米6</h3></a><br/>
<a href="product?id=2"><h3>三星Note8</h3></a><br/>
<a href="product?id=3"><h3>华为9</h3></a><br/>
<a href="product?id=4"><h3>魅族6</h3></a><br/>
</body>
</html>
下面是cart.jsp购物车的jsp
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Map<String,Integer> map=(Map<String,Integer>)request.getSession().getAttribute("cart");
if(map!=null){
for(String key: map.keySet()){
int value=map.get(key);
%>
<h2>名称:<%=key %> 数量:<%=value %></h2>
<%
}
}
%>
</body>
</html>
这里是servlet
package com.dong.servlet;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ProductServlet extends HttpServlet {
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[] goods= {"Iphone8","小米6","三星Note8","华为9","魅族6"};
//取到id对应的商品名称
String name=goods[id];
//2. 获取购物车存放东西的session Map<String , Integer> iphoen7 3
Map<String,Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cart");
//把一个map对象存放到session里面去,并且保证只存一次。
//session里面没有存放过任何东西。
if(map==null) {
map=new LinkedHashMap<String,Integer>();
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("<a href='product.jsp'><h3>继续购物</h3></a>");
response.getWriter().write("<a href='cart.jsp'><h3>回到我的购物车结算</h3></a>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
自己试试吧,说不定会回忆起什么!