Posted on 2008-09-01 00:04
橡皮人 阅读(167)
评论(0) 编辑 收藏
近期刚完成二期的结业项目电子图书,其中主要训练的模块是购物车,后台发布前台显示,代码写的非常粗糙,JSP页面没有使用EL和JSTL,大片大片的<% %>。
首先就其中购物车的增删改和清空购物车做一个笔记。
CartBean:
package com.csthit.store.vo;
public class CartBean {
private Book book; //图书bean
private int quantity; //设置图书数量
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
上面是对购物车的bean组件,下面放置几个对cart进行增删改清空的Servlet代码
String action = request.getParameter("action"); //获得JSP页面的动作参数
HttpSession session = request.getSession(); //获取一个Session对象
String isbn = request.getParameter("isbn"); //以图书的ISBN为条件查询图书
/*
* 添加一本书籍到购物车
*/
if("add".equals(action)) {
String num = request.getParameter("num"); //JSP页面传递的数量参数,默认为1
int quantity = Integer.parseInt(num);
BookDAO bookdao = new BookDAO();
Book book = bookdao.queryByISBN(isbn);
CartBean cb = null;
Map map = null;
if(session.getAttribute("MYCART")!=null) {
map = (HashMap)session.getAttribute("MYCART");
if(map.get(isbn)!=null) {
cb = (CartBean)map.get(isbn);
cb.setQuantity(cb.getQuantity()+quantity);
} else {
cb = new CartBean();
cb.setBook(book);
cb.setQuantity(quantity);
}
map.put(isbn, cb);
} else {
map = new HashMap();
cb = new CartBean();
cb.setBook(book);
cb.setQuantity(quantity);
map.put(isbn, cb);
}
session.setAttribute("MYCART", map);
RequestDispatcher rd = request.getRequestDispatcher("view_cart.jsp");
rd.forward(request, response);
}
/*
* 修改购物车数量
*/
if("modify".equals(action)) {
String num = request.getParameter("num");
int quantity = Integer.parseInt(num);
Map map = (Map)session.getAttribute("MYCART");
CartBean cb = null;
if(quantity==0) { //客户端如果把数量修改为0则删除当前书籍
map.remove(isbn);
} else {
cb = (CartBean)map.get(isbn);
cb.setQuantity(quantity);
map.put(isbn, cb);
}
session.setAttribute("MYCART", map);
RequestDispatcher rd = request.getRequestDispatcher("view_cart.jsp");
rd.forward(request, response);
}
/*
* 删除商品
*/
if("delete".equals(action)) {
Map map = (Map)session.getAttribute("MYCART");
map.remove(isbn);
session.setAttribute("MYCART", map);
RequestDispatcher rd = request.getRequestDispatcher("view_cart.jsp");
rd.forward(request, response);
}
/*
* 清空购物车,使Map的key长度为0
*/
if("remove".equals(action)) {
Map map = (HashMap)session.getAttribute("MYCART");
Object[] keys = map.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
map.remove((String)keys[i]);
}
session.setAttribute("MYCART", map);
RequestDispatcher rd = request.getRequestDispatcher("view_cart.jsp");
rd.forward(request, response);
}