Servlet
ShowServlet
package servlet; import bean.Book; import bean.BookDB; 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 java.io.IOException; import java.io.PrintWriter; import java.util.Collection; //展示图书的界面 @WebServlet("/ShowServlet") public class ShowServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter(); //BookDB中调用方法获取所有图书 Collection<Book> collection=BookDB.getAll(); //遍历集合 for(Book book:collection){ //当“点击购买”,将该图书传递至PurchaseServlet out.print(book.getName()+"<a href='/PurchaseServlet?id="+book.getId()+"'>点击购买</a></br>"); } } }
PurchaseServlet
package servlet; import bean.Book; import bean.BookDB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; //将选择要购买的图书添加进购物车,并展示购物车 @WebServlet("/PurchaseServlet") public class PurchaseServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter(); //获取图书的ID String id=request.getParameter("id"); if(id==null){ response.sendRedirect("/ShowServlet"); return; } //如果id不为空,根据ID获取对应的图书 Book book=BookDB.getbyId(id); //将图书添加进购物车 //购物车存在session域, 因为购物车中不止一种商品,因此用集合存储点击购买的所有图书,集合代表真正的购物车 HttpSession session=request.getSession(); //获取购物车 List<Book> cart=(List)session.getAttribute("bookcart"); //如果购物车不存在 if(cart==null){ //创建集合对象 cart=new ArrayList(); session.setAttribute("bookcart",cart);//将集合对象添加进session域 } //添加商品进购物车 cart.add(book); out.print("您所购买的图书有:<br>"); //遍历集合,查看购物车中的商品 for(Book bookt:cart){ out.print(bookt.getName()+"<br>"); } //将购物车保存下来 Cookie cookie=new Cookie("JSESSIONID",session.getId());//命名cookie的名字为"JSESSIONID",ID为获取到的sessionID cookie.setMaxAge(60*60);//cookie的生存周期 cookie.setPath("/");//保存最大值根 response.addCookie(cookie);//将"cookie"添加到请求头 } }
项目下载