jsp課程(7)---jsp+servlet+javabean 實(shí)現(xiàn)的簡(jiǎn)單網(wǎng)上購(gòu)物車
簡(jiǎn)單購(gòu)物車案例(附源碼)
下面具體流程,很多功能都還未完善,之后會(huì)實(shí)現(xiàn)更多功能,例如分頁(yè),付款等 敬請(qǐng)期待
使用jsp的MVC模型開(kāi)發(fā)購(gòu)物車(jsp+servlet+javabean)
必須有三層架構(gòu)思想:web層負(fù)責(zé)與用戶打交道 業(yè)務(wù)處理層(服務(wù)層 service)數(shù)據(jù)訪問(wèn)層(dao)
//BookDao.javapackage com.hbsi.dao;import java.util.List;import com.hbsi.domain.Book;public interface BookDao {//獲取所有的書public List<Book> getAll();//根據(jù)id獲取書public Book find(String id);}
//BookDaoImpl.javapackage com.hbsi.dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;import com.hbsi.domain.Book;import com.hbsi.utils.DBManager;public class BookDaoImpl implements BookDao{@Overridepublic Book find(String id) {Connection conn = null;PreparedStatement pt = null;ResultSet rs = null;try {conn = DBManager.getConnection();String sql = "select * from book where id=?";pt = conn.prepareStatement(sql);pt.setString(1, id);rs = pt.executeQuery();//Book b = null;if(rs.next()){Book b = new Book();b.setId(rs.getString("id"));b.setName(rs.getString("name"));b.setAuthor(rs.getString("author"));b.setPrice(rs.getDouble("price"));b.setDescription(rs.getString("description"));return b;}return null;} catch (Exception e) {throw new RuntimeException(e);} finally {DBManager.closeDB(conn, pt, rs);}}@Overridepublic List<Book> getAll() {Connection conn = null;PreparedStatement pt = null;ResultSet rs = null;try {conn = DBManager.getConnection();String sql = "select id,name,author,price,description from book";pt = conn.prepareStatement(sql);rs = pt.executeQuery();List<Book> list = new ArrayList<Book>();while (rs.next()) {Book b = new Book();b.setId(rs.getString("id"));b.setName(rs.getString("name"));b.setAuthor(rs.getString("author"));b.setPrice(rs.getDouble("price"));b.setDescription(rs.getString("description"));list.add(b);}return list;} catch (Exception e) {throw new RuntimeException(e);} finally {DBManager.closeDB(conn, pt, rs);}}}
//Book.javapackage com.hbsi.domain;public class Book {private String id;private String name;private String author;private double price;private String description;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 double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}}//Cart.javapackage com.hbsi.domain;import java.util.LinkedHashMap;import java.util.Map;public class Cart {private Map<String,CartItem> map=new LinkedHashMap<String,CartItem>();private double price;//所有購(gòu)物項(xiàng)的價(jià)格總計(jì)public void add(Book book){CartItem item=map.get(book.getId());if(item!=null){item.setQuantity(item.getQuantity()+1);}else{item=new CartItem();item.setBook(book);item.setQuantity(1);//把新的購(gòu)物項(xiàng)添加到map集合中map.put(book.getId(),item);}}public Map<String, CartItem> getMap() {return map;}public void setMap(Map<String, CartItem> map) {this.map = map;}public double getPrice() {double totalprice=0;for(Map.Entry<String, CartItem> me:map.entrySet()){CartItem item=me.getValue();totalprice+=item.getPrice();}this.price=totalprice;return price;}public void setPrice(double price) {this.price = price;}}//CartItem.javapackage com.hbsi.domain;//用于代表購(gòu)買的商品(書)。包括書的數(shù)量。(購(gòu)物項(xiàng),購(gòu)物車的一行)public class CartItem {private Book book;private int quantity;private double price;//對(duì)此類書的價(jià)格計(jì)算(小計(jì))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()*this.quantity;//書的單價(jià)乘以數(shù)量}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}}//businessService.javapackage com.hbsi.service;import java.util.List;import com.hbsi.domain.Book;import com.hbsi.domain.Cart;public interface businessService {public List<Book> getAllBook();//獲取指定id的書public Book findBook(String id);//刪除購(gòu)物項(xiàng)public void deleteCartItem(String sid, Cart cart);//清空購(gòu)物車public void clearCart(Cart cart);//改變數(shù)量public void changeQuantity(String sid, String quantity, Cart cart);}//BusinessServiceImpl.javapackage com.hbsi.service;import java.util.List;import com.hbsi.dao.BookDao;import com.hbsi.dao.BookDaoImpl;import com.hbsi.domain.Book;import com.hbsi.domain.Cart;import com.hbsi.domain.CartItem;public class BusinessServiceImpl implements BusinessService{BookDao dao=new BookDaoImpl();@Overridepublic List<Book> getAllBook() {return dao.getAll();}@Overridepublic void deleteCartItem(String sid, Cart cart) {cart.getMap().remove(sid);}@Overridepublic Book findBook(String id) {return dao.find(id);}@Overridepublic void clearCart(Cart cart) {cart.getMap().clear();}@Overridepublic void changeQuantity(String sid, String quantity, Cart cart) {CartItem item=cart.getMap().get(sid);item.setQuantity(Integer.parseInt(quantity));}}//db.propertiesdriver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/bookdbusername=rootpassword=root//BuyServlet.javapackage com.hbsi.web.controller;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.hbsi.domain.Book;import com.hbsi.domain.Cart;import com.hbsi.service.BusinessServiceImpl;public class BuyServlet extends HttpServlet {BusinessServiceImpl service=new BusinessServiceImpl();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//1.獲取要買的書String sid=request.getParameter("id");Book book =service.findBook(sid);//2.得到購(gòu)物車Cart cart=(Cart)request.getSession().getAttribute("cart");if(cart==null){cart=new Cart();request.getSession().setAttribute("cart", cart);}//3.把數(shù)添加到購(gòu)物車中cart.add(book);response.sendRedirect("./ListCartServlet");//request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}//ChangeQuantitySevlet.javapackage com.hbsi.web.controller;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.hbsi.domain.Cart;import com.hbsi.service.BusinessService;import com.hbsi.service.BusinessServiceImpl;public class ChangeQuantitySevlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String sid = request.getParameter("id");String quantity = request.getParameter("quantity");Cart cart = (Cart) request.getSession().getAttribute("cart");BusinessService service = new BusinessServiceImpl();service.changeQuantity(sid,quantity,cart);request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}//ClearCartServlet.java package com.hbsi.web.controller;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.hbsi.domain.Cart;import com.hbsi.service.BusinessService;import com.hbsi.service.BusinessServiceImpl;public class ClearCartServlet extends HttpServlet {BusinessService service=new BusinessServiceImpl();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {Cart cart=(Cart) request.getSession().getAttribute("cart");service.clearCart(cart);request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}//DeleteItemServlet.javapackage com.hbsi.web.controller;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.hbsi.domain.Cart;import com.hbsi.service.BusinessService;import com.hbsi.service.BusinessServiceImpl;public class DeleteItemServlet extends HttpServlet {//調(diào)服務(wù)類里邊的方法從購(gòu)物項(xiàng)里刪除想要?jiǎng)h除的書B(niǎo)usinessService service=new BusinessServiceImpl();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//獲取到購(gòu)物項(xiàng)String sid=request.getParameter("id");Cart cart=(Cart)request.getSession().getAttribute("cart");service.deleteCartItem(sid,cart);request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}//ListBookServlet.javapackage com.hbsi.web.controller;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.hbsi.domain.Book;import com.hbsi.service.BusinessService;import com.hbsi.service.BusinessServiceImpl;public class ListBookServlet extends HttpServlet {BusinessService service=new BusinessServiceImpl();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {List<Book> list=service.getAllBook();request.setAttribute("books", list);request.getRequestDispatcher("../WEB-INF/jsp/listbook.jsp").forward(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}//ListCartServlet.javapackage com.hbsi.web.ui;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/jsp/listcart.jsp").forward(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}//listbook.jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><%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 'listbook.jsp' starting page</title> </head> <body style="text-align:center"> <h2>淵博書店</h2> <table border="1" width="80%"> <tr> <td>編號(hào)</td> <td>書名</td> <td>作者</td> <td>價(jià)格</td> <td>描述</td> <td>操作</td> </tr> <c:forEach var="book" items="${books}"> <tr> <td>${book.id}</td> <td>${book.name}</td> <td>${book.author}</td> <td>${book.price}</td> <td>${book.description}</td> <td> <a href="${pageContext.request.contextPath}/servlet/BuyServlet?id=${book.id}">加入購(gòu)物車</a> </td> </tr> </c:forEach> </table> </body></html>//listcart.jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><%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 'listbook.jsp' starting page購(gòu)物顯示頁(yè)面</title> <script type="text/javascript"> function deleteItem(id){ var b = window.confirm("確定要?jiǎng)h除嗎?"); if(b){window.location.href="${pageContext.request.contextPath}/servlet/DeleteItemServlet?id="+id; } } function clearcart(){ var b = window.confirm("確定要清空您當(dāng)前所選的商品嗎?"); if(b){window.location.href="${pageContext.request.contextPath}/servlet/ClearCartServlet"; } } function changequantity(input,id,oldvalue){ //得到修改的數(shù)量 var quantity = input.value; //判斷是否是正整數(shù) if(quantity<0 || quantity!=parseInt(quantity)){ alert("請(qǐng)輸入正整數(shù)??!"); input.value=oldvalue; return; } var b = window.confirm("確定要將數(shù)量修改為:"+quantity); if(b){window.location.href="${pageContext.request.contextPath}/servlet/ChangeQuantitySevlet?id="+id+"&quantity="+quantity; } } </script> </head> <body style="text-align:center"> <h1> 您的購(gòu)物車</h1> <h2>您購(gòu)買了如下商品</h2> <c:if test="${empty cart.map}"> <font color="red">您的購(gòu)物車還是空的哦??!</font><br/> <img src="../images/gouwuche.jpg" width="350" height="350"/> 您可以 <a href="${pageContext.request.contextPath}/servlet/ListBookServlet">點(diǎn)擊此處進(jìn)入購(gòu)買頁(yè)面</a> </c:if> <c:if test="${!empty cart.map}"> <table border="1" width="80%" bordercolor="blue"> <tr> <td>編號(hào)</td> <td>書名</td> <td>單價(jià)</td> <td>數(shù)量</td> <td>小計(jì)</td> <td>操作</td> </tr> <c:forEach var="me" items="${cart.map}"> <tr> <td>${me.key}</td> <td>${me.value.book.name}</td> <td>${me.value.book.price}¥</td> <td> <input type="text" name="quantity" value="${me.value.quantity}" onchange="changequantity(this,${me.key},${me.value.quantity})"/> 在此修改數(shù)量 </td> <td>${me.value.price}¥</td> <td> <a href="javascript:deleteItem(${me.key })" >刪除</a> <!--<a href="javascript:void(0)" onclick="deleteItem(${me.key })">刪除</a>--> <!--<a href="${pageContext.request.contextPath}/servlet/DeleteItemServlet?id=${me.key}">刪除</a>--> </td> </tr> </c:forEach> <tr> <td colspan="3">總價(jià)(totalprice)</td> <td colspan="1">${cart.price }¥</td> <td> <!--<a href="${pageContext.request.contextPath}/servlet/ClearCartServlet">清空購(gòu)物車</a>--> <a href="javascript:clearcart()">清空購(gòu)物車</a> </td> <td> <a href="javascript:pay()">去結(jié)算</a></td> </tr> </table> <a href="${pageContext.request.contextPath}/servlet/ListBookServlet">返回繼續(xù)購(gòu)物</a> </c:if> </body></html>//index.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> <base href="<%=basePath%>"> <title>網(wǎng)上購(gòu)物首頁(yè)</title> </head> <body> <font color="red" size="15px"> 想要你的書架上再多幾本書嗎?</font><br/>點(diǎn)擊圖片進(jìn)入 <a href="${pageContext.request.contextPath}/servlet/ListBookServlet"> <img src="./images/book.jpg" width="350" height="350"/> </a> </body></html>
//DBConn.java
package com.hbsi.utils;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class DBConn {private static Connection conn=null;public static Connection getConn(){if(conn==null){try {Class.forName("com.mysql.jdbc.Driver");try {conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/bookdb?user=root&password=root&useUnicode=true&characterEncoding=UTF-8");} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return conn;}public static void realse(ResultSet rs, PreparedStatement pstmt) {if(rs!=null){try {rs.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(pstmt!=null){try {pstmt.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
//DBManager.java
package com.hbsi.utils;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;public class DBManager {/** * @param args */static String driver;static String url;static String username;static String password;static{InputStream in=DBManager.class.getClassLoader().getResourceAsStream("db.properties");Properties pro=new Properties();try {pro.load(in);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}driver = pro.getProperty("driver");url = pro.getProperty("url");username = pro.getProperty("username");password = pro.getProperty("password");try {Class.forName(driver);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static Connection getConnection(){Connection con=null;try {con=DriverManager.getConnection(url,username,password);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return con;}public static void closeDB(Connection con,Statement st,ResultSet rs){if(rs!=null){try {rs.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(st!=null){try {st.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(con!=null){try {con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static void main(String[] args) {getConnection();}}
聯(lián)系客服