JavaNote 4.6 session中实现简单购物车功能

一、添加商品

package com.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "AddServlet",urlPatterns = "/addcart")
public class AddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        HttpSession session = request.getSession();
        List list = (List)session.getAttribute("list");
        if(list==null){
//第一次访问时,session中没有attribute属性
             list = new ArrayList();
        }
        list.add(name);
        session.setAttribute("list",list);
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(3600);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
二、添加商品html

    

商品列表

杯子 书包 笔记本

三、获取商品

package com.session;

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;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "GetCartServlet",urlPatterns = "/recart")
public class GetCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        List list = (List)session.getAttribute("list");
        response.setContentType("text/html;charset=utf-8");
        for(String s : list){
            response.getWriter().write(s);
        }
    }
}

 

你可能感兴趣的:(Java,Note)