package com.itheima.web;
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.ArrayList; import java.util.List;
/**
-
添加商品到购物车的Servlet */ @WebServlet("/addCart") public class AddCartServlet extends HttpServlet {
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.解决乱码问题 req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); //2.获取请求参数 String productName = req.getParameter("product");
//2.获取服务端的会话对象 HttpSession session = req.getSession(); //---------完善购物车的案例:------------- //看看是不是已经添加过商品到购物车了 List<String> productInfo = (List<String>)session.getAttribute("productInfo"); if(productInfo == null){ //还没有添加商品到购物车,创建一个新的购物车 productInfo = new ArrayList<>(); } //把新的商品存到购物车里 productInfo.add(productName); //----------完善购物车的案例:------------------ //3.添加购物车集合到服务端会话对象的共享区域中 session.setAttribute("productInfo",productInfo);//此时是把信息都添加到了服务器的内存之中。每个会话都有自己独立的内存空间 //4.告知浏览器已经添加好了 resp.getWriter().write("已经添加好了,可以查看购物车了。"); resp.getWriter().write("<a href='/showCartInfo'>现在查看?</a>"); resp.getWriter().write("<a href='/index.html'>回到主页</a>");} } ` package com.itheima.web;
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("/showCartInfo") public class ShowCartInfoServlet extends HttpServlet {
/**
- 获取共享的购物车信息
- @param req
- @param resp
- @throws ServletException
- @throws IOException
*/
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.解决乱码问题
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//2.获取会话对象
HttpSession session = req.getSession();
//3.使用会话对象获取共享数据
List productInfo = (List)session.getAttribute("productInfo");
//4.如果没有共享的购物车信息,就提示还没有添加
if(productInfo == null){
resp.getWriter().write("您还没有添加商品到购物车,现在添加?");
}else {
//5.判断如果有共享的购物车信息,就输出
for (String productName : productInfo) {
resp.getWriter().write("您添加的商品是:"+productName+"
"); } } } }
`