Session简单购物车实现
2019-05-23 / JAVA / 1786 次围观 / 0 次吐槽 /显示书列表:
@WebServlet("/BookAll")
public class BookAll extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write("图书列表 <br/>");
//显示书籍列表
for(Entry<Integer, Book> entry : DBUtil.getAllBook().entrySet()) {
String html = "<a href='"+req.getContextPath()+"/ShoppingCart?id="+entry.getKey()+"'>"+entry.getValue().getName()+" 点击添加购物车</a><br/>";
resp.getWriter().write(html);
}
resp.getWriter().write("查看购物车:" + "<a href='"+req.getContextPath()+"/ShoppingCart"+"'>购物车</a>");
}
}添加购物车和显示购物车:
@WebServlet("/ShoppingCart")
public class ShoppingCart extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
//查询ID
String id = req.getParameter("id");
if(id != null) {
Book book = DBUtil.findBookById(Integer.parseInt(id));
//查看session
HttpSession session = req.getSession();
List<Book> shoppingCart = (List<Book>)session.getAttribute("ShoppingCart");
if(shoppingCart == null) {//如果不存在,创建新列表
shoppingCart = new ArrayList<Book>();
}
//添加到列表
shoppingCart.add(book);
//保存至session
session.setAttribute("ShoppingCart", shoppingCart);
resp.getWriter().write("添加购物车成功:" + book.toString());
}else {
//查看session
HttpSession session = req.getSession();
List<Book> shoppingCart = (List<Book>)session.getAttribute("ShoppingCart");
if(shoppingCart == null) {
resp.getWriter().write("购物车里还没有东西!");
}else {
resp.getWriter().write("购物车列表:<br/>");
for(Book b : shoppingCart) {
resp.getWriter().write(b + "<br/>");
}
}
}
}
}- 上一篇:Cookie模拟查看书的历史记录
- 下一篇:Session简单实现验证码登录
Powered By Cheug's Blog
Copyright Cheug Rights Reserved.