session实现简易购物车Demo

使用session实现一个简易的购物车demo,主要就是将物品添加到购物车,以及清空购物车,不涉及数据库操作,使用Map存放物品信息。

简易添加商品界面(太过简易,四个超链接 add.jsp)

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




Insert title here


ad钙奶


泡面


香肠


雀巢


接下来就是它的kindservlet(处理商品添加)

这里用数组存放商品信息,然后用map容器商品为键,商品数量为值,它的流程是首先用map去接受request.getsession.getAttribute里的值,你没、setAttribute,那它肯定为空啊,所以首先setAttribute,然后第一次将它的第一个商品和数量1存放到map中,接下来如果商品重复了数量就加一,否则将它的商品和数量1存放到map中,最后有两个超链接,继续购买和清空购物车。

public class KindServlet extends HttpServlet {
	
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		int id = Integer.parseInt(request.getParameter("id"));
		String []names= {"ad钙奶","泡面","香肠","雀巢"};
		String name=names[id];
		Map map=(Map) request.getSession().getAttribute("kind");
		if(map==null)
		{
			map=new HashMap();
			request.getSession().setAttribute("kind", map);
		}
		if(map.containsKey(name))
		{
		map.put(name,map.get(name)+1);
	}else
	{
		map.put(name,1);
	}
		response.getWriter().write("

继续购买

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

去购物车结算

"); } /** * @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); } }

接下来是购物车信息展示界面(简易show.jsp)

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




Insert title here


购物车商品:

<% Mapmap=(Map)session.getAttribute("kind"); if(map!=null) { for(String key:map.keySet()) { int val=map.get(key); System.out.print(val); %>

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

<% } } %> 清空购物车

清空购物车的clearservlet(就是将它的Attribute  remove掉或者终止这个session都可以)

public class ClearServlet extends HttpServlet {
	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().removeAttribute("kind");
response.sendRedirect("./session/show.jsp");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

效果:添加商品界面

session实现简易购物车Demo_第1张图片

商品信息界面

session实现简易购物车Demo_第2张图片

清空购物车后界面

session实现简易购物车Demo_第3张图片

你可能感兴趣的:(java,web学习)