使用会话完成一个简单的购物车
如何使用会话存取数据:
存数据:
1.获取HttpSession对象:HttpSession session = request.getSession();
2.session.setAttribute("name", somethingToStore);
取数据:
1.获取HttpSession对象:HttpSession session = request.getSession();
2.somethingToStore something = session.getAttribute("name");
删除数据:
1.获取HttpSession对象:HttpSession session = request.getSession();
2.session.removeAttribute("name");
功能描述:
1.在jsp页面中显示商品列表
2.添加商品到购物车
3.浏览购物车
4.清空购物车
功能实现:
1.数据模型:使用一个静态的map(以商品ID为键,以商品名称为值)表示整个商品列表,使用另一个map(以商品ID为键,以商品数量为值)来表示某种商品的数量
2逻辑处理:当需要添加一个商品时,需要获得该商品的ID,把它作为请求参数传递到浏览购物车页面,然后将该ID取出,以此为键,增加会话中购物车相应商品的数量;
当需要清空购物车时,将购物车从会话中移去
3.显示:显示购物车:遍历表示购物车的map,得到每种商品的ID和数量,通过商品的ID再结合表示商品列表的map就可以得到商品的名称,有了商品的名称和数量,就可以处理显示工作
显示商品列表:遍历表示商品列表的map,得到每个商品和对应的ID,然后没每个商品添加一个购买链接(以商品ID为请求参数)
在部署描述符中配置会话:
<jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <url-pattern>*.jspf</url-pattern> <page-encoding>UTF-8</page-encoding> <scripting-invalid>false</scripting-invalid> <include-prelude>/WEB-INF/jsp/base.jspf</include-prelude> <trim-directive-whitespaces>true</trim-directive-whitespaces> <default-content-type>text/html</default-content-type> </jsp-property-group> </jsp-config> <session-config> <session-timeout>30</session-timeout><!-- 会话的存活时间为30分钟 --> <cookie-config> <http-only>true</http-only> </cookie-config>
<!--使用Cookie技术追踪会话ID--> <tracking-mode>COOKIE</tracking-mode> </session-config>
StoreServlet.java
import java.io.IOException; import java.util.HashMap; import java.util.Hashtable; 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; import javax.servlet.http.HttpSession; @WebServlet( name = "storeServlet", urlPatterns = "/shop" ) public class StoreServlet extends HttpServlet{ // 创建一个静态数据库 private final Map<Integer, String> products = new Hashtable<>(); public StoreServlet(){ this.products.put(1, "Sandpaper"); this.products.put(2, "Nails"); this.products.put(3, "Paint"); this.products.put(5, "Tape"); } // 在doGet()中实现3中操作----brows、addToCart和viewCart @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if(action == null) action = "browse"; switch(action){ case "addToCart": this.addToCart(request, response); break; case "viewCart": this.viewCart(request, response); break; case "emptyCart": this.emptyCart(request, response); break; case "browse": default: this.browse(request, response); break; } } private void emptyCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().removeAttribute("cart"); response.sendRedirect("shop?action=viewCart"); } private void browse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("products", this.products); request.getRequestDispatcher("/WEB-INF/jsp/view/browse.jsp").forward(request, response); } private void viewCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("products", this.products); request.getRequestDispatcher("/WEB-INF/jsp/view/viewCart.jsp").forward(request, response); } private void addToCart(HttpServletRequest request, HttpServletResponse response) throws IOException { int productId; try { productId = Integer.parseInt(request.getParameter("productId")); } catch (Exception e) { response.sendRedirect("shop"); return; } HttpSession session = request.getSession(); if(session.getAttribute("cart") == null) session.setAttribute("cart", new HashMap<Integer, Integer>()); // 存储商品数量 @SuppressWarnings("unchecked") Map<Integer, Integer> cart = (Map<Integer, Integer>) session.getAttribute("cart"); if(!cart.containsKey(productId)) cart.put(productId, 0); cart.put(productId, cart.get(productId) + 1); response.sendRedirect("shop?action=viewCart"); } }
browse.jsp
<%@ page import="java.util.Map" %> <!DOCTYPE html> <html> <head> <title>Product List</title> </head> <body> <h2>Product List</h2> <a href="<c:url value="shop?action=viewCart"/>">View Cart</a><br/><br/> <% Map<Integer, String> products = (Map<Integer, String>)request.getAttribute("products"); for(int id : products.keySet()){ %> <a href=" <c:url value="/shop"> <c:param name="action" value="addToCart"/> <c:param name="productId" value="<%= Integer.toString(id) %>" /> </c:url> "><%= products.get(id) %></a><br/> <% } %> </body> </html>
viewCart.jsp
<%@ page import="java.util.Map" %> <!DOCTYPE html> <html> <head> <title>View Cart</title> </head> <body> <h2>View Cart</h2> <a href="<c:url value="/shop"/>">Product List</a><br/><br/> <% Map<Integer, String> products = (Map<Integer, String>)request.getAttribute("products"); Map<Integer, Integer> cart = (Map<Integer, Integer>) session.getAttribute("cart"); if(cart == null || cart.size() == 0) out.print("Your cart is empty."); else{ for(int id : cart.keySet()){ out.println(products.get(id) + " (qty: " + cart.get(id) + ")<br/>"); } } %> <a href="<c:url value="/shop?action=emptyCart"/>">Empty Cart</a><br/> </body> </html>
base.jspf
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
运行结果:
商品列表:
点击购买链接后查看购物车:
清空购物车: