《簡易商城購物系統》
大家經常去網上夠物,對網上所謂的購物車應該不會陌生吧,那么今天我們就用使用javaweb的MVC設計模式來實現一個網上購物系統的案例。
最終效果如下:
三層架構的簡單介紹
一、開發步驟
首先要搞清楚你要做什么,然后:
1.搭建開發環境
jstl.jar
standard.jar
2.建立類包
3.建立數據庫
使用內存數據庫
總之,此購物車的實現,使用的是MVC設計模式,MVC設計模式的思路就是從jsp--javabean—servlet--jsp頁面做顯示
流程圖:
圖一:MVC設計模式的簡介
圖二:購物系統案例的實現思路:
圖三:設計購物車頁面
節日正式開始,精彩不容錯過。。。。
1.寫一個jsp購物頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% 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>飄葉網上商城</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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <hr/> <h2 >歡迎進入飄葉網上購物商城</h2> <hr> <a href="${pageContext.request.contextPath}/ListBookServlet">進入購物頁面</a> <br> </body> </html>
2.寫一個javabean
package cn.itcast.cart.domain; public class Book { private String id; private String name;//書名 private String author;//作者 private int price; public Book() { super(); // TODO Auto-generated constructor stub } public Book(String id, String name, String author, int price) { super(); this.id = id; this.name = name; this.author = author; this.price = price; } 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; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }
3.建立DB,用Map集合來模擬數據庫
package cn.itcast.cart.domain; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; public class DB { // 使用map集合來模擬數據庫 private static Map<String , Book> books=new LinkedHashMap<String, Book>(); static{ books.put("1", new Book("1", "《水滸傳》", "施耐庵", 48)); books.put("2", new Book("2", "《西游記》", "吳承恩 ", 58)); books.put("3", new Book("3", "《三國演義》", "羅貫中", 78)); books.put("4", new Book("4", "《紅樓夢》", "曹雪芹", 28)); books.put("5", new Book("5", "《平凡的世界》", "路遙", 18)); } // 獲得所有圖書 // 獲得所有圖書 public static Collection<Book> getAll() { return books.values(); } // 根據id查找圖書 public static Book find(String id) { return books.get(id); } }
4.用javabean建立一個購物車對象
package cn.itcast.cart.domain; public class ShoppingcartItem { //購物車項,每一本書買了多少本,總共多少錢 private Book book; private int quantity; private int price; 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; this.price=this.book.getPrice()*quantity; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }
購物車—cart
package cn.itcast.cart.domain; import java.util.HashMap; import java.util.Map; //購物車對象 public class Shoppingcart { private Map<String, ShoppingcartItem> items=new HashMap<String, ShoppingcartItem>(); private int price;//總價 public Map<String, ShoppingcartItem> getItems() { return items; } public void setItems(Map<String, ShoppingcartItem> items) { this.items = items; } public int getPrice() { //計算總價 int price=0; for(ShoppingcartItem item:items.values()) { price+=item.getPrice(); } return price; } public void setPrice(int price) { this.price = price; } }
5、獲得圖書商品列表的servlet—ListBookServlet.java
package cn.itcast.cart.web.servlet; import java.io.IOException; import java.util.Collection; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.cart.domain.Book; import cn.itcast.cart.domain.DB; public class ListBookServlet extends HttpServlet { //從DB中查詢所有的圖書 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //查詢所有的商品 Collection<Book> books = DB.getAll(); // 轉發給jsp顯示 request.setAttribute("books", books); request.getRequestDispatcher("/WEB-INF/pages/listbook.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
6.servlet處理完的數據轉發到一個展示商品的頁面—listbook.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!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=UTF-8"> <title>顯示所有的商品</title> <script type="text/javascript"> function buy(id){ window.location = "${pageContext.request.contextPath}/BuyServlet?id="+id; } </script> </head> <body style="text-align: center"> <h1 >商品列表</h1> <table border="1" width="400px"> <tr> <td>圖書名稱</td> <td>作者</td> <td>價格</td> <td>購買</td> </tr> <c:forEach var="book" items="${requestScope.books}"> <tr> <td>${book.name}</td> <td>${book.author}</td> <td>${book.price}</td> <td> <input type="button" value="購買" onclick="buy(${book.id})"/> </td> </tr> </c:forEach> </table> </body> </html>
7.寫一個購買處理的servlet
package cn.itcast.cart.web.servlet; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.cart.domain.Book; import cn.itcast.cart.domain.DB; import cn.itcast.cart.domain.Shoppingcart; import cn.itcast.cart.domain.ShoppingcartItem; public class BuyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //購買頁面 //獲得圖書 String id=request.getParameter("id"); Book book=DB.find(id); // 獲得購物車 Shoppingcart cart = (Shoppingcart) request.getSession().getAttribute("cart"); if(cart==null){ //首次購物 cart=new Shoppingcart(); request.getSession().setAttribute("cart", cart); } // 商品放入購物車 bookInCart(book,cart); // 跳轉至購物車頁面,是一個請求重定向的頁面 response.sendRedirect(request.getContextPath()+"/ListCartServlet"); } //購物 private void bookInCart(Book book, Shoppingcart cart) {//判斷是否買過 Map<String, ShoppingcartItem> items = cart.getItems(); ShoppingcartItem item = items.get(book.getId()); if(item==null){ //此書未買過,創建新條目 item=new ShoppingcartItem(); item.setBook(book); item.setQuantity(1); //條目存入購物車 items.put(book.getId(), item); }else{ //買過數量加1 item.setQuantity(item.getQuantity()+1); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
8.寫一個獲得購物車數據處理的servlet—ListCartServlet.java
package cn.itcast.cart.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ListCartServlet extends HttpServlet { //查看購物車,請求重定向的頁面 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/WEB-INF/pages/listcart.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
9.購買的東西放入購物車,繼而轉向購物車展示頁面—listcart.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%-- 只要使用foreach就要導入下面的這句代碼--%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!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=UTF-8"> <title>購物車頁面</title> <script type="text/javascript"> function change(id,inputObj){ var quantity=inputObj.value; if(quantity==null || quantity=="") { alert("數量不能為空"); inputObj.value = defaultValue; return; } if(quantity.match(/^[1-9][0-9]*$/)==null) { alert("數量必須為正整數"); inputObj.value = defaultValue; return; } if(parseInt(quantity)>999) { alert("您購買的數量已達到團購標准,請致電800-820-8820"); inputObj.value = defaultValue; return; } window.location="${pageContext.request.contextPath}/UpdateServlet?id="+id+"&quantity="+quantity; } </script> </head> <body style="text-align: center"> <h1>我的購物車</h1><br> <hr> <table border="1" width="800px"> <tr> <td>商品名稱</td> <td>單價</td> <td>數量</td> <td>小計</td> <td>操作</td> </tr> <%--map迭代完后都是entry--%> <c:forEach var="entry" items="${cart.items}"> <tr> <td>${entry.value.book.name}</td> <td>${entry.value.book.price}</td> <td> <input type="text" value="${entry.value.quantity}" onblur="change(${entry.key},this) " style="width: 40px;"/> </td> <td>${entry.value.price}</td> <td> <a href="${pageContext.request.contextPath}/DaleServlet?id=${entry.key }">刪除</a> </td> </tr> </c:forEach> <tr> <td> <a href="${pageContext.request.contextPath}/clearServlet">清空購物車</a> </td> <td> <a href="${pageContext.request.contextPath}/ListBookServlet">繼續購物</a> </td> <td> <a href="#">下訂單</a> </td> <td colspan="2">購物車總價:¥${cart.price}元</td> </tr> </table> </body> </html>
下面就是實現購物車里面的一些操作功能
10.更新購物車,就是修改完數量后,自動更新購物車—UpdateServlet.java
package cn.itcast.cart.web.servlet; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.cart.domain.Shoppingcart; import cn.itcast.cart.domain.ShoppingcartItem; public class UpdateServlet extends HttpServlet { //更新購物車 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲得id和quantity String id=request.getParameter("id"); int quantity=Integer.parseInt(request.getParameter("quantity")); //獲得購物車 Shoppingcart cart = (Shoppingcart) request.getSession().getAttribute("cart"); // 修改數量 /* Map<String, ShoppingcartItem> items = cart.getItems(); ShoppingcartItem item = items.get(id); item.setQuantity(quantity);*/ cart.getItems().get(id).setQuantity(quantity); // 跳轉至購物車頁面 response.sendRedirect(request.getContextPath() + "/ListCartServlet"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
11.刪除購物車中的單行數據—DaleServlet.java
package cn.itcast.cart.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.cart.domain.Shoppingcart; public class DaleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲得id String id = request.getParameter("id"); // 獲得購物車 Shoppingcart cart = (Shoppingcart) request.getSession().getAttribute("cart"); //刪除條目 cart.getItems().remove(id); // 跳轉至購物車頁面 response.sendRedirect(request.getContextPath()+"/ListCartServlet"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
12.清空購物車—clearServlet.java
package cn.itcast.cart.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.cart.domain.Shoppingcart; public class clearServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲得購物車 Shoppingcart cart = (Shoppingcart) request.getSession().getAttribute("cart"); // 清空購物車 cart.getItems().clear(); // 跳轉至購買頁面 response.sendRedirect(request.getContextPath()+"/ListBookServlet"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
ok,忙碌到半夜,到此結束,下面看看我們的最終效果吧:
--------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
嘿嘿,沒有美工處理的頁面,還行,像那回事吧?
這上面的所有功能都可以實現的哦!








