ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
1.addcart.html ~~~ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <center> <h1>商品列表</h1> <a href="/hello/addcart?name=杯子">杯子</a><br> <a href="/hello/addcart?name=书包">书包</a><br> <a href="/hello/addcart?name=笔记本">笔记本</a><br> </center> </body> </html> ~~~ AddCartServlet.java ~~~ package zyw.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 = "AddCartServlet",urlPatterns = "/addcart") public class AddCartServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.获取到商品的信息 String name = request.getParameter("name"); //2.保存商品信息到session HttpSession session = request.getSession(); //List list=new ArrayList(); List list =(List)session.getAttribute("list");//这样商品才不会覆盖 if(list==null){//第一次访问list不存在,需要创建一个list list=new ArrayList(); } list.add(name); session.setAttribute("list",list); //session持久化操作 Cookie cookie = new Cookie("JSESSIONID", session.getId()); cookie.setMaxAge(60*60*24); cookie.setPath("/hello"); response.addCookie(cookie); } } ~~~ GetCartServlet.java ~~~ package zyw.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 = "/getcart") 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<String> list = (List<String>) session.getAttribute("list"); response.setContentType("text/html;charset=utf-8"); for (String s : list) { response.getWriter().write(s+"<br/>"); } } } ~~~ 先访问addcart.html点击商品加入购物车,再GetCartServlet.java获取购物车商品