用JSP實現的商城購物車模組

來源:互聯網
上載者:User

標籤:des   style   http   java   color   使用   

 

這兩天,在學習JSP,正好找個小模組來練練手:

    下面就是實現購物車模組的頁面效果:

圖1. 產品顯示頁面 通過此頁面進行產品選擇,添?到購物車

 

圖2 .購物車頁面

 

圖3 . 商品數量設定

 

好了,先不貼圖了,直接上代碼;先看看項目的文檔結構把(麻雀雖小,五髒俱全):

 

整個項目包括三個類,兩個JSP頁面,以下分別把他們的代碼貼上:

 

Cart.java

package shopping.cart;import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class Cart {List<CartItem> items = new ArrayList<CartItem>();public List<CartItem> getItems() {return items;}public void setItems(List<CartItem> items) {this.items = items;}public void add(CartItem ci) {for (Iterator<CartItem> iter = items.iterator(); iter.hasNext();) {CartItem item = iter.next();if(item.getProduct().getId() == ci.getProduct().getId()) {item.setCount(item.getCount() + 1);return;}}items.add(ci);}public double getTotalPrice() {double d = 0.0;for(Iterator<CartItem> it = items.iterator(); it.hasNext(); ) {CartItem current = it.next();d += current.getProduct().getPrice() * current.getCount();}return d;}public void deleteItemById(String productId) {for (Iterator<CartItem> iter = items.iterator(); iter.hasNext();) {CartItem item = iter.next();if(item.getProduct().getId().equals(productId)) {iter.remove();return;}}}}


 

CartItem.java

 

package shopping.cart;import shopping.cart.Product;public class CartItem {private Product product;private int count;public int getCount() {return count;}public void setCount(int count) {this.count = count;}public Product getProduct() {return product;}public void setProduct(Product product) {this.product = product;}}


 

 Product.java

package shopping.cart;import java.io.Serializable;public class Product implements Serializable {private String id;// 產品標識private String name;// 產品名稱private String description;// 產品描寫敘述private double price;// 產品價格public Product() {}public Product(String id, String name, String description, double price) {this.id = id;this.name = name;this.description = description;this.price = price;}public void setId(String id) {this.id = id;}public void setName(String name) {this.name = name;}public void setDescription(String description) {this.description = description;}public void setPrice(double price) {this.price = price;}public String getId() {return id;}public String getName() {return name;}public String getDescription() {return description;}public double getPrice() {return price;}}


 

以下是倆JSP頁面原始碼:

ShowProducts.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%><%@ page import="shopping.cart.*"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>My JSP ‘ShowProductsJSP.jsp‘ starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"></head><body bgcolor="#ffffff"><%Map products = new HashMap();products.put("1", new Product("1", "mp3播放器","效果非常不錯的mp3播放器,儲存空間達1GB", 100.00));products.put("2", new Product("2", "數位相機", "象素500萬,10倍光學變焦",500.00));products.put("3", new Product("3", "數位攝像機","120永珍素,支援夜景拍攝,20倍光學變焦", 200.00));products.put("4", new Product("4", "迷你mp4","市面所能見到的最好的mp4播放器,國產", 300.00));products.put("5", new Product("5", "多功能手機","集mp3播放、100永珍素數位相機,手機功能於一體", 400.00));products.put("6", new Product("6", "多功能手機111","集mp3播放23、100永珍素數位相機111,手機功能於一體111",600.00));products.put("7", new Product("7", "11111111111","集mp3播放23、100永珍素數位相機111,手機功能於一體111",700.00));products.put("8", new Product("8", "2222222222","集mp3播放23、100永珍素數位相機111,手機功能於一體111",800.00));products.put("9", new Product("9", "33333333333333","集mp3播放23、100永珍素數位相機111,手機功能於一體111",900.00));session.setAttribute("products", products);%><H1>產品顯示</H1><form name="productForm"action="http://localhost:8088/JSPlearning/ShopCartJSP.jsp"method="POST"><input type="hidden" name="action" value="purchase"><table border="1" cellspacing="0"><tr bgcolor="#CCCCCC"><tr bgcolor="#CCCCCC"><td>序號</td><td>產品名稱</td><td>產品描寫敘述</td><td>產品單價(¥)</td>                        <td>加入?到購物車</td></tr><%Set productIdSet = products.keySet();Iterator it = productIdSet.iterator();int number = 1;while (it.hasNext()) {String id = (String) it.next();Product product = (Product) products.get(id);%><tr><td><%=number++%></td><td><%=product.getName()%></td><td><%=product.getDescription()%></td><td><%=product.getPrice()%></td><td><a href="Buy.jsp?id=<%=product.getId()%>&action=add" target="cart">我要購買</a></td></tr><%}%></table><p></p></form></body></html>


 

Buy.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%><%@ page import="shopping.cart.*" %><%Cart c = (Cart)session.getAttribute("cart");if(c == null) {c = new Cart();session.setAttribute("cart", c);}double totalPrice = c.getTotalPrice();request.setCharacterEncoding("GBK");String action = request.getParameter("action");Map products = (HashMap)session.getAttribute("products");if(action != null && action.trim().equals("add")) {String id = request.getParameter("id");Product p = (Product)products.get(id);CartItem ci = new CartItem();ci.setProduct(p);ci.setCount(1);c.add(ci);}if(action != null && action.trim().equals("delete")) {String id = request.getParameter("id");c.deleteItemById(id);}if(action != null && action.trim().equals("update")) {for(int i=0; i<c.getItems().size(); i++) {CartItem ci = c.getItems().get(i);int count = Integer.parseInt(request.getParameter("p" + ci.getProduct().getId()));ci.setCount(count);}} %> <%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%List<CartItem> items = c.getItems();%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB18030"><title>購物車</title></head><body><!-- c的值是:<%=(c == null) %> items的值是:<%=(items == null) %> --><form action="Buy.jsp" method="get"><input type="hidden" name="action" value="update"/><table align="center" border="1"><tr><td>產品ID</td><td>產品名稱</td><td>購買數量</td><td>單價</td><td>總價</td><td>處理</td></tr><%for(Iterator<CartItem> it = items.iterator(); it.hasNext(); ) {CartItem ci = it.next();%><tr><td><%=ci.getProduct().getId() %></td><td><%=ci.getProduct().getName() %></td><td><input type="text" size=3 name="<%="p" + ci.getProduct().getId() %>" value="<%=ci.getCount() %>" onkeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;"onchange="document.forms[0].submit()"></td><td><%=ci.getProduct().getPrice() %></td><td><%=ci.getProduct().getPrice()*ci.getCount() %></td><td><a href="Buy.jsp?action=delete&id=<%=ci.getProduct().getId() %>">刪除</a></td></tr><%}%><tr><td colspan=3 align="right">全部商品總價格為:</td><td colspan=3><%=c.getTotalPrice() %></td></tr><tr><!--<td colspan=3> <a href="javascript:document.forms[0].submit()">改動</a> </td>  --><td colspan=6 align="right"><a href="">下單</a></td></tr></table></form></body></html>


 

配置好相關檔案,在tomcat中公布後,在瀏覽器中輸入http://localhost:8088/shopCart/ShowProducts.jsp 就可以進入產品展示頁面,其他動作都能夠在頁面上完畢!

注意:我使用的tomcatport(8088)被自己改過,假設沒改過tomcatport的童鞋,預設port為8080。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.