Posted on 2008-08-08 14:06
橡皮人 阅读(130)
评论(0) 编辑 收藏
寫一個簡單的購物車模塊,不提供修改數量。
Servlet如下:
public class InputCart extends HttpServlet {
Book book = null; //bean組件
Map map=null;
RequestDispatcher rd = null;
HttpSession session = null;
String isbn=null;
BookDAO bookdao = new BookDAO();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
session = request.getSession();
String shopping=request.getParameter("shopping");//因為當初考慮到用戶會做到修改商品數量,因為用一個Session對象判斷用戶所進行的操作
//判断客户端是否是在进行购物
if("add".equals(shopping)) {
isbn=request.getParameter("isbn");//獲取隱藏表單域傳遞過來的值
book=bookdao.queryByISBN(isbn); //拿到当前isbn对应的商品信息
if(session.getAttribute("MyCart")!=null) { //判断购物车是否存在商品
map=(HashMap)session.getAttribute("MyCart");
} else {
map=new HashMap();
}
map.put(isbn, book);
session.setAttribute("MyCart", map);
rd=request.getRequestDispatcher("displayBook.jsp");
rd.forward(request, response);
}
}
}
JSP頁面:
<%
Map map=(HashMap)session.getAttribute("MyCart");
Book book=null;
Object[] obj=null;//此數組為拿到Map的Key對象
%>
<body>
<table border="2" width="480">
<tr>
<th class="tdtitle"><font size=4>ISBN</font></th>
<th class="tdtitle"><font size=4>書名</font></th>
<th class="tdtitle"><font size=4>圖片介紹</font></th>
<th class="tdtitle"><font size=4>價格</font></th>
</tr>
<%
if(map!=null) {
Set key=map.keySet();
obj=key.toArray();
for(int i=0;i<obj.length;i++) {
book=(Book)map.get(obj[i]);
%>
<tr>
<td class="tdl"><%=book.getIsbn() %></td>
<td class="tdl"><%=book.getTitle() %></td>
<td class="tdl"><img src="/store/images/<%=book.getImageFile() %> " width="90" height="80"/></td>
<td class="tdl"><%=book.getPrice() %></td>
</tr>
<%
}
} else {
%>
<tr>
<td class="tdl"><font color="red" >当前购物车没有物品!</font></td>
</tr>
<%
}
%>
OK,簡單的購物車雛形寫好了。