//將購物車產品加入到cookie中,方式同瀏覽記錄。
Java實現購物車,方式一(簡易版):存儲在session中。這種方式實現還不嚴謹,大家看的時候看思路即可。
(1). JSP頁面中,選擇某一款產品,將產品id一並傳遞給Servlet進行接收。
```
<a href="<%=path %>/servlet/do_home_control?param=addShoppingCar&ep_id=${p.ep_id}">放入購物車</a>
```
(2). 在Servlet中接收用戶傳遞的參數。
```
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String param = request.getParameter("param");
String path = request.getContextPath();
PrintWriter out = response.getWriter();
if ("addShoppingCar".equals(param)) {
String ep_id = request.getParameter("ep_id");
// 根據key值從session中獲取map對象
Map<String, Easybuy_Product> shoppingCarMap = (Map<String, Easybuy_Product>) request
.getSession().getAttribute("shoppingCar");
// 首次創建
if (shoppingCarMap == null) {
shoppingCarMap = new HashMap<String, Easybuy_Product>();
}
if (!Tool.isNull(ep_id)) {
// 根據ep_id獲得產品對象
Easybuy_Product ep = productService.getProductByEp_Id(Tool
.strToInt(ep_id));
// 判斷map中是否存在此id
if (shoppingCarMap.containsKey(ep_id)) {
// 如果包含,則根據ep_id獲得Easybuy_Product對象
Easybuy_Product easybuy_Product = shoppingCarMap.get(ep_id);
easybuy_Product.setEp_sum(easybuy_Product.getEp_sum() + 1);
shoppingCarMap.put(ep_id, easybuy_Product);
} else {
ep.setEp_sum(1);
shoppingCarMap.put(ep_id, ep);
}
// 將session寫回去
request.getSession()
.setAttribute("shoppingCar", shoppingCarMap);
}
response.sendRedirect(request.getContextPath() + "/shopping.jsp");
}
```
其中,Tool類中寫了一個公共方法isNull,用來判斷變量是否為null
```
/**
* 非空驗證
*
* @param args
*/
public static boolean isNull(String pageString) {
if (pageString == null || "".equals(pageString)) {
return true;
} else {
return false;
}
}
```
Java實現購物車,方式二:根據用戶的登錄狀態,如果用戶沒有登錄,則用戶加入到購物車中的產品,存儲到session中;如果用戶登錄,則將用戶購物車中的產品存儲到數據庫中或者從數據庫中讀取數據顯示購物車列表。
具體實現如下:
(1). JSP頁面中,選擇某一款產品,將產品id一並傳遞給Servlet進行接收。
```
<a href="<%=path %>/servlet/do_home_control?id=${p.ep_id}&price=${p.ep_price}">放入購物車</a>
```
(2). 在Servlet中,接收產品ID.
```
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
ProductService ps = new ProductServiceImpl();
PrintWriter out = response.getWriter();
String path=request.getContextPath();
String a = request.getParameter("id");
int id = 0;
//如果a==null,說明用戶直接點擊購物車超鏈接進入此頁面;否則用戶通過選擇產品,將此產品加入到購物車
if(a!=null){
id=Integer.parseInt(a);
}
String price=request.getParameter("price");
//判斷用戶是否登錄
User user = (User) request.getSession().getAttribute("userName");
if(user==null){
//說明用戶沒有登錄,也是允許用戶加入購物車的。此時購物車信息存放到session里面
Map<Integer,Product> myCart = (Map<Integer, Product>) request.getSession().getAttribute("MyCart");
if(id != 0){
//根據產品id獲得產品
Product product = ps.getById(id);
if(myCart == null){
//說明是第一次加入購物車
myCart = new HashMap<Integer, Product>();
myCart.put(id, product);
}else{
if(myCart.containsKey(id)){
//如果購物車中存在此商品id,則商品數量加1
Product product1 = myCart.get(id);
product1.setCount(product1.getCount()+1);
myCart.put(id, product1);
}else{
myCart.put(id, product);
}
}
}
request.getSession().setAttribute("MyCart", myCart);
request.getSession().setMaxInactiveInterval(10*60);
}else{
Map<Integer,Product> myCart = (Map<Integer, Product>) request.getSession().getAttribute("MyCart");
if(myCart == null){
if(id != 0){
//根據產品ID獲取一條購物車信息
Shopping shoppingItem = sService.getShoppingItemByEp_ID(id);
if(shoppingItem == null){
//如果不存在,則第一次加入此產品 insert
sService.insert(id,price,1,user.getEu_user_id());
}else{
shoppingItem.setEod_quantity(shoppingItem.getEod_quantity()+1);
//更新
sService.updateShoppingItem(shoppingItem);
}
}
}else{
//便利session
Set<Integer> keys = myCart.keySet();
Iterator<Integer> iterator = keys.iterator();
while (iterator.hasNext()) {
Product p = myCart.get(iterator.next());
//根據用戶名和產品id判斷此產品是否存在;如果存在,更新數量,如果不存在,則插入
if(sService.isExistByUser_EpId(user.getEu_user_id(),p.getEp_id())){
Shopping shoppingItem = sService.getShoppingItemByEp_ID(p.getEp_id());
if(p.getEp_id() == id){
p.setCount(p.getCount()+1);
}
shoppingItem.setEod_quantity(shoppingItem.getEod_quantity()+p.getCount());
sService.updateShoppingItem(shoppingItem);
}else{
sService.insert(id,price,p.getCount(),user.getEu_user_id());
}
}
request.getSession().removeAttribute("MyCart");
}
//最后往前台返回的是一個購物車產品列表
List<Shopping> shoppings = sService.getShoppintCartByUserId(user.getEu_user_id());
request.getSession().setAttribute("shoppings",shoppings);
}
out.print("<script type='text/javascript'>location='"
+path
+ "/shopping.jsp';</script>");
}
```
(3). 在JSP頁面中顯示購物車列表
```
<table>
<tr>
<th>商品名稱</th>
<th>商品價格</th>
<th>購買數量</th>
<th>操作</th>
</tr>
<c:choose>
<c:when test="${userName==null }">
<c:choose>
<c:when test="${MyCart==null||MyCart.size()==0 }">
您還未添加商品到購物車!
</c:when>
<c:otherwise>
<c:forEach items="${MyCart}" var="cart">
<tr id="product_id_1">
<td class="thumb"><img src="${cart.value.ep_file_name }" /><a
href="product-view.jsp">${cart.value.ep_name}</a></td>
<td class="price" id="price_id_1"><span>${cart.value.ep_price}</span>
<input type="hidden" value="${cart.value.ep_price}" />
</td>
<td class="number">
<dl>
<dt>
<input id="number_id_1" type="text" name="number"
value="${cart.value.count }" />
</dt>
<dd onclick="reloadPrice(1,true);">修改</dd>
</dl>
</td>
<td class="delete"><a href="javascript:delShopping(1);">刪除</a>
</td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
</c:when>
<c:otherwise>
<c:choose>
<c:when test="${shoppings.size()==0 }">
您還未添加商品到購物車!
</c:when>
<c:when test="${shoppings==null }">
<c:redirect url="${path }/DoshoppingServlet"></c:redirect>
</c:when>
<c:otherwise>
<c:forEach items="${shoppings}" var="shopping">
<tr id="product_id_1">
<td class="thumb"><img src="-------" /><a
href="product-view.jsp">${shopping.ep_id}</a></td>
<td class="price" id="price_id_1"><span>${shopping.ep_price}</span>
<input type="hidden" value="${shopping.ep_price}" />
</td>
<td class="number">
<dl>
<dt>
<input id="number_id_1" type="text" name="number"
value="${shopping.eod_quantity }" />
</dt>
<dd onclick="reloadPrice(1,true);">修改</dd>
</dl>
</td>
<td class="delete"><a href="javascript:delShopping(1);">刪除</a>
</td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
</c:otherwise>
</c:choose>
</table>
```
我個人認為方式二更好一些,也更貼近生活中用的淘寶功能。
以上功能,時間有些緊迫,有不足之處歡迎大家指正。
謝謝你來看我。