Servlet Session(httpsession)实现简易购物车
假设我们要在网上买书,那么我们通过session实现添加到购物车,并可以查看购物车的功能。
1. 模拟一个数据库,我们先写一个Book类,该类封装Book的相关信息,这里简单起见,主要有ID号,书名,以及购买的本数。
/** * 模拟数据库 */ final public class DB { private static HashMap<String, Book> hm = null; private DB(){ } static{ hm = new LinkedHashMap<String, Book>(); Book book1 = new Book("1", "Java基础", 0); Book book2 = new Book("2", "Oracle数据库", 0); Book book3 = new Book("3", "C语言", 0); Book book4 = new Book("4", "Python核心教程", 0); Book book5 = new Book("5", "Web技术", 0); hm.put(book1.getId(),book1); hm.put(book2.getId(),book2); hm.put(book3.getId(),book3); hm.put(book4.getId(),book4); hm.put(book5.getId(),book5); } /** * 得到数据库中所有的书 * @return */ public static HashMap<String, Book> getBooks(){ return hm; } /** * 根据ID得到书 * @param id * @return */ public static Book getBookById(String id){ if(hm.containsKey(id)){ return hm.get(id); } return null; } }
2. Servlet中读取数据库中所有的书的信息,显示在页面上
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<h2>欢迎光临</h2>"); out.println("<table border=1>"); HashMap<String, Book> books = DB.getBooks(); Iterator it = books.keySet().iterator(); while(it.hasNext()){ Book book = books.get(it.next()); out.println("<tr><td>"+book.getName()+"</td><td><a href='/MyCart/BuyBookCl?id="+book.getId()+"'>点击购买</a></td></tr>"); } out.println("</table>"); }
3. 当用户点击购买的链接时,传递书的id号,跳到BuyBookCl这个Servlet进行处理
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); //接收用户购买书的名字 String id = request.getParameter("id"); String name = DB.getBookById(id).getName(); HttpSession session = request.getSession(); // 用HashMap更简单 // 从session中得到购买的 书 HashMap<String,Book> books = (HashMap<String,Book>) session.getAttribute("books"); if(books == null){ books = new LinkedHashMap<String,Book>(); } if(books.containsKey(id)){ Book book = books.get(id); book.setNum(book.getNum()+1); }else{ Book book = new Book(id, name, 1); books.put(id, book); } session.setAttribute("books", books); // 转发到ShowMyCart查看购物车 request.getRequestDispatcher("/ShowMyCart").forward(request, response); }
运行结果
我们接收到书的id后,然后从Session中取出保存购物车信息的HashMap,如果这个HashMap为空,则新建一个HashMap;如果这个HashMap不为空,则去查找是否存在该书的ID号,如果已经存在,说明之前已经购买过该书,则将这本书的数量加1,,反之将新购买的书添加进去,并且数量设置为1。
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。