注:這裏只是簡單演示,不少代碼並非那麼完善,且 沒有寫支付功能,只是簡單演示整個流程而已html
2.一、數據庫相關表前端
1 CREATE TABLE orders( -- 訂單表 2 id VARCHAR(100) PRIMARY KEY, 3 orderId VARCHAR(100) NOT NULL UNIQUE, 4 num INT, 5 price FLOAT(8,2), 6 state INT, 7 user_id VARCHAR(100), 8 CONSTRAINT user_id_fk FOREIGN KEY(user_id) REFERENCES Users(id) 9 ); 10 11 CREATE TABLE ordersitem( -- 訂單項表 12 id VARCHAR(100) PRIMARY KEY, 13 num INT, 14 price FLOAT(8,2), 15 orders_id VARCHAR(100), 16 book_id VARCHAR(100), 17 CONSTRAINT orders_id_fk FOREIGN KEY(orders_id) REFERENCES orders(id), 18 CONSTRAINT book_id_fk FOREIGN KEY(book_id) REFERENCES book(id) 19 );
2.二、實體類java
1 package com.shore.entity; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 /** 7 * @author DSHORE/2019-4-26 8 * 9 */ 10 //訂單信息:對應的就是購物車的基本信息 11 public class Orders{ 12 private String id;//訂單:用戶+訂單項 數據庫中:只有用戶的id 只有訂單項的id 13 private String orderId;//訂單號。not null unique 14 private int num;//數量 15 private float price;//付款金額 16 private int state;//0表示未發貨 1表示已發貨 17 private List<OrdersItem> items = new ArrayList<OrdersItem>();//訂單中的訂單項 //id 18 private User user;//id //該訂單是屬於哪一個用戶 19 20 public String getId() { 21 return id; 22 } 23 24 public void setId(String id) { 25 this.id = id; 26 } 27 28 public String getOrderId() { 29 return orderId; 30 } 31 32 public void setOrderId(String orderId) { 33 this.orderId = orderId; 34 } 35 36 public int getNum() { 37 return num; 38 } 39 40 public void setNum(int num) { 41 this.num = num; 42 } 43 44 public float getPrice() { 45 return price; 46 } 47 48 public void setPrice(float price) { 49 this.price = price; 50 } 51 52 public int getState() { 53 return state; 54 } 55 56 public void setState(int state) { 57 this.state = state; 58 } 59 60 public List<OrdersItem> getItems() { 61 return items; 62 } 63 64 public void setItems(List<OrdersItem> items) { 65 this.items = items; 66 } 67 68 public User getUser() { 69 return user; 70 } 71 72 public void setUser(User user) { 73 this.user = user; 74 } 75 }
OrdersItem 訂單項 實體類web
1 package com.shore.entity; 2 3 /** 4 * @author DSHORE/2019-4-26 5 * 6 */ 7 //對應購物車中的購物項 8 public class OrdersItem { 9 private String id; 10 private int num; 11 private float price; 12 private Book book; 13 14 public String getId() { 15 return id; 16 } 17 public void setId(String id) { 18 this.id = id; 19 } 20 public int getNum() { 21 return num; 22 } 23 public void setNum(int num) { 24 this.num = num; 25 } 26 public float getPrice() { 27 return price; 28 } 29 public void setPrice(float price) { 30 this.price = price; 31 } 32 public Book getBook() { 33 return book; 34 } 35 public void setBook(Book book) { 36 this.book = book; 37 } 38 }
2.三、接口和實現類sql
OrderDao接口數據庫
1 package com.shore.dao; 2 3 import java.util.List; 4 5 import com.shore.entity.Orders; 6 import com.shore.entity.User; 7 8 /** 9 * @author DSHORE/2019-4-26 10 * 11 */ 12 public interface OrderDao { 13 //前臺內容 14 void addOrders(Orders orders, User user);//添加訂單信息(即:用戶付款後,將該信息添加到個人訂單中) 15 List<Orders> findOrdersByUsersId(String id);//根據用戶的id查詢屬於本身的訂單 16 Orders findOrdersById(String ordersId);//根據id查看訂單的詳細信息 17 18 //後臺訂單發貨處理 19 List<Orders> findOrdersByState(int i);//顯示全部未發貨的訂單,還要查詢出是哪一個用戶的 20 void sureOrders(String ordersId);//把已寄出的商品,改爲已發貨狀態 21 }
OrderDaoImpl 接口的實現類session
1 package com.shore.dao.impl; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.util.ArrayList; 8 import java.util.List; 9 10 import com.shore.dao.OrderDao; 11 import com.shore.entity.Book; 12 import com.shore.entity.Orders; 13 import com.shore.entity.OrdersItem; 14 import com.shore.entity.User; 15 import com.shore.util.IdGeneratorKey; 16 import com.shore.util.JdbcUtil; 17 18 /** 19 * @author DSHORE/2019-4-26 20 * 21 */ 22 public class OrderDaoImpl implements OrderDao { 23 Connection connection = null; 24 PreparedStatement pStatement = null; 25 ResultSet resultSet = null; 26 27 //添加訂單信息(即:用戶付款後,將該信息添加到個人訂單中。即 :保存到數據庫的訂單表中) 28 public void addOrders(Orders orders, User user) { 29 connection = JdbcUtil.getConnection(); 30 try { 31 String sql = "insert into orders (id,orderId,num,price,state,user_id) values(?,?,?,?,?,?);"; 32 pStatement = connection.prepareStatement(sql); 33 //String orderId = IdGeneratorKey.genOrdersId(); 34 //String ids = IdGeneratorKey.getPrimaryKey();//這兩個都不須要,直接從實體類中獲取(servlet獲取頁面中的值,已經存到實體類中了) 35 pStatement.setString(1,orders.getId()); 36 pStatement.setString(2,orders.getOrderId()); 37 pStatement.setInt(3,orders.getNum()); 38 pStatement.setFloat(4,orders.getPrice()); 39 pStatement.setInt(5,orders.getState()); 40 pStatement.setString(6,user.getId()); 41 pStatement.executeUpdate(); 42 //訂單中的訂單項 43 List<OrdersItem> items = orders.getItems(); 44 if(items != null && items.size() > 0){//訂單項中 有東西,才添加進數據庫中的訂單項表 45 String sql2 = "insert into ordersitem (id,num,price,orders_id,book_id) values(?,?,?,?,?)"; 46 pStatement = connection.prepareStatement(sql2); 47 Object pps[][] = new Object[items.size()][]; 48 for(int i = 0; i < items.size(); i++){ 49 String id = IdGeneratorKey.getPrimaryKey(); 50 OrdersItem item = items.get(i); 51 pStatement.setString(1,id); 52 pStatement.setInt(2,item.getNum()); 53 pStatement.setFloat(3,item.getPrice()); 54 pStatement.setString(4,orders.getId()); 55 pStatement.setString(5,item.getBook().getId()); 56 pStatement.executeUpdate(); 57 } 58 } 59 } catch (SQLException e) { 60 e.printStackTrace(); 61 }finally{ 62 JdbcUtil.close(connection, pStatement, resultSet); 63 } 64 } 65 66 //根據用戶的id查詢屬於本身的訂單 67 public List<Orders> findOrdersByUsersId(String id) { 68 connection = JdbcUtil.getConnection(); 69 try { 70 pStatement = connection.prepareStatement("select * from orders where user_id=? order by orderId desc;"); 71 pStatement.setString(1,id); 72 resultSet = pStatement.executeQuery(); 73 List<Orders> list=new ArrayList<Orders>(); 74 Orders order = null; 75 while(resultSet.next()){ 76 //建立Orders對象 77 order = new Orders(); 78 order.setId(resultSet.getString("id")); 79 order.setOrderId(resultSet.getString("orderId")); 80 order.setNum(resultSet.getInt("num")); 81 order.setState(resultSet.getInt("state")); 82 order.setPrice(resultSet.getFloat("price")); 83 //order.setUser(rs.getString("user_id")); 84 list.add(order); 85 } 86 return list; 87 } catch (SQLException e) { 88 e.printStackTrace(); 89 throw new RuntimeException(); 90 }finally{ 91 JdbcUtil.close(connection, pStatement, resultSet); 92 } 93 } 94 95 //根據id查看訂單的詳細信息(訂單明細、圖書明細、當前用戶,都要查詢出來) 96 public Orders findOrdersById(String ordersId) { 97 connection = JdbcUtil.getConnection(); 98 try { 99 pStatement = connection.prepareStatement("select * from orders where id=?"); 100 pStatement.setString(1,ordersId); 101 resultSet = pStatement.executeQuery(); 102 Orders orders = null; 103 while(resultSet.next()){ 104 //建立Orders對象 105 orders = new Orders(); 106 orders.setId(resultSet.getString("id")); 107 orders.setOrderId(resultSet.getString("orderId")); 108 orders.setNum(resultSet.getInt("num")); 109 orders.setState(resultSet.getInt("state")); 110 orders.setPrice(resultSet.getFloat("price")); 111 //orders.setUser(rs.getString("user_id")); 112 } 113 if(orders != null){ 114 //查詢用戶信息:少的一方,無論有沒有需求,默認都是查出來的 115 pStatement = connection.prepareStatement("select * from Users where id=(select user_id from orders where id=?)"); 116 pStatement.setString(1,ordersId); 117 resultSet = pStatement.executeQuery(); 118 User user = null; 119 while(resultSet.next()){ 120 //建立User對象 121 user = new User(); 122 user.setId(resultSet.getString("id")); 123 user.setUserName(resultSet.getString("userName")); 124 user.setPassWord(resultSet.getString("passWord")); 125 user.setCellPhone(resultSet.getString("cellPhone")); 126 user.setMobilePhone(resultSet.getString("mobilePhone")); 127 user.setAddress(resultSet.getString("address")); 128 user.setEmail(resultSet.getString("email")); 129 } 130 orders.setUser(user); 131 //訂單明細 132 pStatement = connection.prepareStatement("select * from ordersitem where orders_id=?"); 133 pStatement.setString(1,ordersId); 134 resultSet = pStatement.executeQuery(); 135 List<OrdersItem> items=new ArrayList<OrdersItem>(); 136 OrdersItem or=null; 137 while(resultSet.next()){ 138 or=new OrdersItem(); 139 or.setId(resultSet.getString("id")); 140 or.setNum(resultSet.getInt("num")); 141 or.setPrice(resultSet.getFloat("price")); 142 items.add(or); 143 } 144 //查詢圖書的信息 145 if(items != null && items.size() > 0){ 146 pStatement = connection.prepareStatement(("select * from Book where id=(select book_id from ordersitem where id=?)")); 147 for(OrdersItem item:items){ 148 pStatement.setString(1,item.getId()); 149 resultSet = pStatement.executeQuery(); 150 Book book = null; 151 while(resultSet.next()){ 152 book = new Book(); 153 book.setId(resultSet.getString("id")); 154 book.setName(resultSet.getString("name")); 155 book.setAuthor(resultSet.getString("author")); 156 book.setPrice(resultSet.getFloat("price")); 157 book.setImage(resultSet.getString("image")); 158 book.setDescription(resultSet.getString("description")); 159 book.setCategory_id(resultSet.getString("category_id")); 160 item.setBook(book); 161 } 162 } 163 } 164 orders.setItems(items); 165 } 166 return orders; 167 }catch (SQLException e) { 168 e.printStackTrace(); 169 throw new RuntimeException(); 170 }finally{ 171 JdbcUtil.close(connection, pStatement, resultSet); 172 } 173 } 174 175 //下面幾個方法 都是 後臺內容 訂單發貨處理 176 //顯示全部未發貨的訂單,還要查詢出是哪一個用戶的 177 public List<Orders> findOrdersByState(int i) { 178 connection = JdbcUtil.getConnection(); 179 try { 180 pStatement = connection.prepareStatement("select * from orders where state=? order by orderId desc"); 181 pStatement.setInt(1,i); 182 resultSet = pStatement.executeQuery(); 183 List<Orders> lo = new ArrayList<Orders>(); 184 Orders order = null; 185 while(resultSet.next()){ 186 order = new Orders(); 187 order.setId(resultSet.getString("id")); 188 order.setOrderId(resultSet.getString("orderId")); 189 order.setNum(resultSet.getInt("num")); 190 order.setState(resultSet.getInt("state")); 191 order.setPrice(resultSet.getFloat("price")); 192 //order.setUser(rs.getString("user_id")); 193 lo.add(order); 194 } 195 if(lo != null && lo.size() > 0){ 196 //查詢用戶信息:少的一方,無論有沒有需求,默認都是查出來的 197 pStatement = connection.prepareStatement("select * from Users where id=(select user_id from orders where id=?)"); 198 for(Orders ord:lo){ 199 pStatement.setString(1,ord.getId()); 200 resultSet = pStatement.executeQuery(); 201 while(resultSet.next()){ 202 User user = new User(); 203 user.setId(resultSet.getString("id")); 204 user.setUserName(resultSet.getString("userName")); 205 user.setPassWord(resultSet.getString("passWord")); 206 user.setCellPhone(resultSet.getString("cellPhone")); 207 user.setMobilePhone(resultSet.getString("mobilePhone")); 208 user.setAddress(resultSet.getString("address")); 209 user.setEmail(resultSet.getString("email")); 210 ord.setUser(user); 211 } 212 } 213 } 214 return lo; 215 } catch (SQLException e) { 216 e.printStackTrace(); 217 throw new RuntimeException(); 218 }finally{ 219 JdbcUtil.close(connection, pStatement, resultSet); 220 } 221 } 222 223 //把已寄出的商品,改爲已發貨狀態 224 public void sureOrders(String ordersId) { 225 connection = JdbcUtil.getConnection(); 226 try { 227 pStatement = connection.prepareStatement("update orders set state=? where id=?"); 228 pStatement.setInt(1,1); 229 pStatement.setString(2,ordersId); 230 pStatement.executeUpdate(); 231 } catch (SQLException e) { 232 e.printStackTrace(); 233 }finally{ 234 JdbcUtil.close(connection, pStatement, resultSet); 235 } 236 } 237 }
2.四、Servlet 控制器jsp
ClientServlet 類post
1 package com.shore.web.controller.client; 2 3 import java.io.IOException; 4 import java.util.ArrayList; 5 import java.util.List; 6 import java.util.Map; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import javax.servlet.http.HttpSession; 13 14 import com.shore.entity.Cart; 15 import com.shore.entity.CartItem; 16 import com.shore.entity.Orders; 17 import com.shore.entity.OrdersItem; 18 import com.shore.entity.User; 19 import com.shore.service.OrderService; 20 import com.shore.service.impl.OrderServiceImpl; 21 import com.shore.util.IdGeneratorKey; 22 23 /** 24 * @author DSHORE/2019-5-12 25 * 26 */ 27 public class ClientServlet extends HttpServlet { 28 private static final long serialVersionUID = 1L;//序列化 29 OrderService oService = new OrderServiceImpl(); 30 31 public void doGet(HttpServletRequest request, HttpServletResponse response) 32 throws ServletException, IOException { 33 String operation = request.getParameter("operation"); 34 if ("genOrders".equals(operation)) { 35 genOrders(request,response); 36 }else if ("showUsersOrders".equals(operation)) { 37 showUsersOrders(request,response); 38 }else if ("showOrdersDetail".equals(operation)) { 39 showOrdersDetail(request,response); 40 } 41 } 42 43 //查看訂單的詳細信息 44 private void showOrdersDetail(HttpServletRequest request, 45 HttpServletResponse response) throws ServletException, IOException { 46 String ordersId = request.getParameter("ordersId");//取得訂單的id(訂單號) 47 Orders ordersDetail = oService.findOrdersById(ordersId);//訂單的明細還要查出來;明細中還要查詢出書的信息 48 request.setAttribute("ordersDetail", ordersDetail); 49 request.getRequestDispatcher("/client/showOrdersDetail.jsp").forward(request, response); 50 } 51 52 //根據用戶的id查詢屬於本身的訂單 53 private void showUsersOrders(HttpServletRequest request, 54 HttpServletResponse response) throws ServletException, IOException { 55 //判斷用戶是否登陸:若是還沒登陸,則轉向登陸頁面 56 HttpSession session = request.getSession(); 57 User user = (User)session.getAttribute("user"); 58 if(user == null){ 59 request.setAttribute("message", "請先登陸,2秒後將自動跳轉到登陸頁面!<meta http-equiv='Refresh' content='2;URL="+request.getContextPath()+"/client/login.jsp'>"); 60 request.getRequestDispatcher("/client/message.jsp").forward(request, response); 61 return; 62 } 63 List<Orders> UserOrders = oService.findOrdersByUsersId(user.getId());//查詢某個用戶的全部訂單 64 request.setAttribute("UserOrders", UserOrders); 65 request.getRequestDispatcher("/client/listOrders.jsp").forward(request, response); 66 } 67 68 //付款購買:把訂單和訂單項的信息存入數據庫中(生成訂單) 69 private void genOrders(HttpServletRequest request, 70 HttpServletResponse response) throws ServletException, IOException { 71 //判斷用戶是否登陸:若是還沒登陸,則轉向登陸頁面 72 HttpSession session = request.getSession(); 73 User user = (User)session.getAttribute("user"); 74 if(user == null){ 75 request.setAttribute("message", "請先登陸,2秒後將自動跳轉到登陸頁面!<meta http-equiv='Refresh' content='2;URL="+request.getContextPath()+"/client/login.jsp'>"); 76 request.getRequestDispatcher("/client/message.jsp").forward(request, response); 77 return; 78 } 79 String id = IdGeneratorKey.getPrimaryKey();//(UUID)自動生成:訂單id 80 String ordersId = IdGeneratorKey.genOrdersId();//自動生成:訂單號 81 //若是已登陸,則從session中取出購物車中商品:Cart Map<String,CartItem> 填充模型 82 Cart cart = (Cart) session.getAttribute("cart");//購物車 83 Orders orders = new Orders();//訂單 84 orders.setId(id); 85 orders.setNum(cart.getNum()); 86 orders.setPrice(cart.getPrice()); 87 orders.setState(0); 88 orders.setOrderId(ordersId); 89 //購物項 90 List<OrdersItem> ordersItems = new ArrayList<OrdersItem>(); 91 for(Map.Entry<String,CartItem> item:cart.getItems().entrySet()){ 92 CartItem cartItem = item.getValue(); 93 String orderItemId = IdGeneratorKey.getPrimaryKey(); 94 OrdersItem orderItem = new OrdersItem(); 95 //修改 96 orderItem.setId(orderItemId); 97 orderItem.setNum(cartItem.getNum()); 98 orderItem.setPrice(cartItem.getPrice()); 99 orderItem.setBook(cartItem.getBook()); 100 ordersItems.add(orderItem); 101 } 102 orders.setItems(ordersItems); 103 oService.addOrders(orders,user); 104 session.removeAttribute("cart");//付款後,清空session中的購物車 105 request.setAttribute("message", "付款成功,請等待店家發貨!<span style='font-size: 18px;'><br/><br/>也可點擊「個人訂單」,查看您的訂單信息</span>");//中間的付款步驟沒寫,這裏只是模擬了購物的流程 106 request.getRequestDispatcher("/client/message.jsp").forward(request, response); 107 } 108 109 public void doPost(HttpServletRequest request, HttpServletResponse response) 110 throws ServletException, IOException { 111 doGet(request, response); 112 } 113 }
2.五、前端頁面ui
listOrders.jsp 主頁面
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@include file="/client/header.jsp"%> 3 <style> 4 table tr th{ border:1px solid #C1C1C1; font-size: 16px;} 5 table,table tr td { border:1px solid #C1C1C1; } 6 table { width: 71%; min-height: 25px; line-height: 25px; border-collapse: collapse; padding:2px; margin:auto;text-align: center;} 7 </style> 8 9 <h2 style="text-align: center;font-size: 20px">如下是您近期的訂單</h2> 10 <table> 11 <tr> 12 <th>訂單號</th> 13 <th>金額</th> 14 <th>訂單狀態</th> 15 <th>訂單詳情</th> 16 </tr> 17 <c:forEach items="${UserOrders}" var="uo"> 18 <tr> 19 <td>${uo.orderId}</td> 20 <td>¥${uo.price}元</td> 21 <td>${uo.state==0?'未發貨':'已發貨'}</td> 22 <td> 23 <a href="${pageContext.request.contextPath}/ClientServlet?operation=showOrdersDetail&ordersId=${uo.id}">查看明細</a> 24 </td> 25 </tr> 26 </c:forEach> 27 </table>
showOrdersDetail.jsp 明細頁面
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@include file="/client/header.jsp"%> 3 <style> 4 table tr th{ border:1px solid #C1C1C1; font-size: 16px;} 5 table,table tr td { border:1px solid #C1C1C1; } 6 table { width: 71%; min-height: 25px; line-height: 25px; border-collapse: collapse; padding:2px; margin:auto;text-align: center;} 7 </style> 8 9 <div style="font-size: 15px;"> 10 訂單號:${ordersDetail.orderId} 11 總金額:¥${ordersDetail.price}元 明細以下:<br/> 12 </div> 13 <table> 14 <tr> 15 <th>書名</th> 16 <th>做者</th> 17 <th>單價</th> 18 <th>數量</th> 19 <th>小計</th> 20 </tr> 21 <c:forEach items="${ordersDetail.items}" var="od"> 22 <tr> 23 <td>${od.book.name}1</td> 24 <td>${od.book.author}</td> 25 <td>¥${od.book.price}元</td> 26 <td>${od.num }</td> 27 <td>¥${od.price}元</td> 28 </tr> 29 </c:forEach> 30 </table> 31 <div style="text-align:left;width:280px; margin:0 auto;font-size: 15px;"> 32 收貨信息以下:<br/> 33 地址:${ordersDetail.user.address }<br/> 34 電話:${ordersDetail.user.cellPhone }<br/> 35 </div>
原創做者:DSHORE 做者主頁:http://www.cnblogs.com/dshore123/ 原文出自:http://www.javashuo.com/article/p-hubuknau-s.html 歡迎轉載,轉載務必說明出處。(若是本文對您有幫助,能夠點擊一下右下角的 推薦,或評論,謝謝!) |