首页 > 代码库 > session 购物车

session 购物车

package session;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionDemo4 extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Book book = (Book)Db.getAll().get(id);
        
        HttpSession session = request.getSession();
        //当前网站名,不能够手动指定而是,通过下面的方法获得
//        request.getContextPath();
        
        //从Session的到用户用于保存所有书的集合(购物车)
        List list = (List) session.getAttribute("list");
        if(list == null){
            list = new ArrayList();
            session.setAttribute("list", list);
        }
        list.add(book);
        
        //重定向到购物车显示页面
        response.sendRedirect(request.getContextPath()+"/ListCarServlet");
    }

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