j假设一个数据库和书对象
//数据库 class Db{ private static Map<String, Book> map = new LinkedHashMap(); static{ map.put("1", new Book("1","web开发","老张")); map.put("2", new Book("2","spring","老毕")); map.put("3", new Book("3","struts","老张")); map.put("4", new Book("4","jdbc","老黎")); } //拿到书 public static Map getAll(){ return map; } } //书对象 class Book{ private String id; private String name; private String author; public Book() { super(); } public Book(String id, String name, String author) { super(); this.id = id; this.name = name; this.author = author; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
将书的列表显示出来
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置防止乱码 response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.write("本网站有如下商品:<br>"); request.getSession(); Map<String,Book> map = Db.getAll(); for(Map.Entry<String,Book> entry : map.entrySet()){ Book book = entry.getValue(); //重写url防止用户禁用cookie String url = response.encodeURL("BuyServlet?id="+book.getId()); out.write(book.getName()+"<a href='"+url+"' target='_blank'>购买</a><br>"); } }
点击购买后
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); //根据id号找到书 Map<String, Book> map = Db.getAll(); Book book = map.get(id); HttpSession session = request.getSession(false); //从session得到书,使用list存放 List list = (List) session.getAttribute("list"); if(list==null){ list = new ArrayList(); session.setAttribute("list", list); } list.add(book); //重写url String url = response.encodeRedirectURL("/day07/ListCartServlet"); response.sendRedirect(url); }
最后显示购买的界面
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置防止乱码 response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); //由session得到书目 HttpSession session = request.getSession(false); //对session进行判断 if(session==null){ out.write("you do not hava to purchase any goods<br>"); return; } out.write("You purchase the following commodity: <br>"); List<Book> list = (List) session.getAttribute("list"); for(Book book : list){ out.write(book.getName()+"<br>"); } }