1. 程式人生 > >Java HttpSession完成簡單購物車功能

Java HttpSession完成簡單購物車功能

HttpSession實現簡單購物車功能如下

  

顯示所有可購買的物品

package com.app2;

import java.io.IOException;
import java.io.PrintWriter;
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("/ShowAllBooksServlet")
public class ShowAllBooksServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("ShowAllBooksServlet doGet()");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		// 顯示所有書籍
		out.write("<h1>書籍清單</h1>");
		Map<String, Book> books = BookDB.findAllBooks();
		for (Map.Entry<String, Book> ele : books.entrySet()) {
			out.write(ele.getValue().getName() + "  " + 
					"<a href='"+request.getContextPath()+"/BuyServlet?id="+ele.getKey()+"' target='_blank'>購買</a><br/>");
		}
		
		// 檢視購物車連結
		out.write("<a href='"+request.getContextPath()+"/ShowCartServlet'>檢視購物車</a>");
	}

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

}
新增到購物車功能
package com.app2;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

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("/BuyServlet")
public class BuyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("BuyServlet doGet()");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		String id = request.getParameter("id");
		Book b = BookDB.findById(id);
		
		// 將物品放入到HttpSession中,List<Book>表示
		HttpSession session = request.getSession();
		List<Book> cart = (List<Book>) session.getAttribute("cart");
		if (cart == null) {
			cart = new ArrayList<Book>();
			session.setAttribute("cart", cart);
		}
		
		// 肯定有購物車了
		cart.add(b);
		
		out.write(b.getName() + "已放入你的購物車 " + "<a href='"+request.getContextPath()+"/ShowAllBooksServlet'>繼續購物</a>");
	}

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

}