This article is a research on the order module in the javaweb bookstore.
1. Create related classes
domain:
Order
OrderItem
dao: OrderDao
service: OrderService
web.servlete: OrderServlet
/** * Order entry class */public class OrderItem { private String iid; private int count;// Quantity private double subtotal;// Subtotal private Order order;// Order private Book book;// Book to be purchased} /** * Order class */public class Order { private String oid; private Date ordertime;// Order time private double total;// Total private int state;// There are four types of order status: 1 Not paid 2 Not paid but not shipped 3 Not shipped but not confirmed receipt 4 Confirmed transaction successful private User owner;// Order owner private String address;// Shipping address private List<OrderItem> orderItemList;// All entries under the current order} public class OrderDao { private QueryRunner qr = new TxQueryRunner(); /** * Add order* @param order */ public void addOrder(Order order) { try { String sql = "insert into orders values(?,?,?,?,?,?)"; /* * Timestamp for processing the conversion of Date of util to SQL */ Timestamp timestamp = new Timestamp(order.getOrdertime().getTime()); Object[] params = {order.getOid(), timestamp, order.getTotal(), order.getState(), order.getOwner().getUid(), order.getAddress()}; qr.update(sql, params); } catch(SQLException e) { throw new RuntimeException(e); } } /** * Insert order entry* @param orderItemList */ public void addOrderItemList(List<OrderItem> orderItemList) { /** * batch(String sql, Object[][] of QueryRunner class params) * where params are multiple one-dimensional arrays! * Each one-dimensional array is executed once with SQL, and multiple one-dimensional arrays are executed multiple times*/ try { String sql = "insert into orderitem values(?,?,?,?,?)"; /* * Convert orderItemList to a two-dimensional array* Convert an OrderItem object to a one-dimensional array*/ Object[][] params = new Object[orderItemList.size()][]; // Loop through the orderItemList and use each orderItem object to assign a value to each one-dimensional array in params for(int i = 0; i < orderItemList.size(); i++) { OrderItem item = orderItemList.get(i); params[i] = new Object[]{item.getIid(), item.getCount(), item.getSubtotal(), item.getOrder().getOid(), item.getBook().getBid()}; } qr.batch(sql, params);//Execute batch processing} catch(SQLException e) { throw new RuntimeException(e); } } /** * Query order by uid* @param uid * @return */ public List<Order> findByUid(String uid) { /* * 1. Query all List<Order> of the current user through uid * 2. Loop through each Order and load all its OrderItem for it */ try { /* * 1. Get all orders for the current user*/ String sql = "select * from orders where uid=?"; List<Order> orderList = qr.query(sql, new BeanListHandler<Order>(Order.class), uid); /* * 2. Loop through each Order and load all its own order entries for it */ for(Order order : orderList) { loadOrderItems(order);//Add all its order entries for the order object} /* * 3. Return order list*/ return orderList; } catch(SQLException e) { throw new RuntimeException(e); } } /** * Load all order entries for the specified order* @param order * @throws SQLException */ private void loadOrderItems(Order order) throws SQLException { /* * Query two tables: orderem, book */ String sql = "select * from orderem i, book b where i.bid=b.bid and oid=?"; /* * Because the result set of a row is no longer a javabean, you can no longer use BeanListHandler, but MapListHandler */ List<Map<String,Object>> mapList = qr.query(sql, new MapListHandler(), order.getOid()); /* * mapList is multiple maps, each map corresponds to a row of result set* One line: * {iid=C7AD5492F27D492189105FB50E55CBB6, count=2, subtotal=60.0, oid=1AE8A70354C947F8B81B80ADA6783155, bid=7, bname=Proficient in Hibernate, price=30.0, author=Zhang Weiqin, image=book_img/8991366-1_l.jpg, cid=2} * ... * * We need to use a map to generate two objects: OrderItem and Book, and then establish the relationship between the two (set Book to OrderItem) */ /* * Loop through each map, use map to generate two objects, and then establish the relationship (the final result is an OrderItem), and save the OrderItem*/ List<OrderItem> orderItemList = toOrderItemList(mapList); order.setOrderItemList(orderItemList); } /** * Convert each Map in the mapList into two objects and establish a relationship* @param mapList * @return */ private List<OrderItem> toOrderItemList(List<Map<String, Object>> mapList) { List<OrderItem> orderItemList = new ArrayList<OrderItem>(); for(Map<String,Object> map : mapList) { OrderItem item = toOrderItem(map); orderItemList.add(item); } return orderItemList; } /** * Convert a Map into an OrderItem object* @param map * @return */ private OrderItem toOrderItem(Map<String, Object> map) { OrderItem orderItem = CommonUtils.toBean(map, OrderItem.class); Book book = CommonUtils.toBean(map, Book.class); orderItem.setBook(book); return orderItem; } /** * Load order* @param oid * @return */ public Order load(String oid) { try { /* * 1. Get all orders of the current user*/ String sql = "select * from orders where oid=?"; Order order = qr.query(sql, new BeanHandler<Order>(Order.class), oid); /* * 2. Load all its entries for order*/ loadOrderItems(order); /* * 3. Return order list*/ return order; } catch(SQLException e) { throw new RuntimeException(e); } } /** * Query order status through oid* @param oid * @return */ public int getStateByOid(String oid) { try { String sql = "select state from orders where oid=?"; return (Integer)qr.query(sql, new ScalarHandler(), oid); } catch(SQLException e) { throw new RuntimeException(e); } } /** * Modify order status* @param oid * @param state * @return */ public void updateState(String oid, int state) { try { String sql = "update orders set state=? where oid=?"; qr.update(sql, state, oid); } catch(SQLException e) { throw new RuntimeException(e); } }} public class OrderService { private OrderDao orderDao = new OrderDao(); /** * Payment method* @param oid */ public void zhiFu(String oid) { /* * 1. Get the status of the order* * If the status is 1, then execute the following code* * If the status is not 1, then this method does nothing*/ int state = orderDao.getStateByOid(oid); if(state == 1) { // Modify the order status to 2 orderDao.updateState(oid, 2); } } /** * Add an order* Transaction required* @param order */ public void add(Order order) { try { // Start the transaction JdbcUtils.beginTransaction(); orderDao.addOrder(order); // Insert the orderDao.addOrderItemList(order.getOrderItemList()); // Insert all entries in the order// Submit the transaction JdbcUtils.commitTransaction(); } catch(Exception e) { // Rollback transaction try { JdbcUtils.rollbackTransaction(); } catch (SQLException e1) { } throw new RuntimeException(e); } } /** * My order* @param uid * @return */ public List<Order> myOrders(String uid) { return orderDao.findByUid(uid); } /** * Load order* @param oid * @return */ public Order load(String oid) { return orderDao.load(oid); } /** * Confirm receipt* @param oid * @throws OrderException */ public void confirm(String oid) throws OrderException { /* * 1. Verify the order status. If it is not 3, throw an exception */ int state = orderDao.getStateByOid(oid);//Get the order status if(state != 3) throw new OrderException("The order confirmation failed, you are not a good thing! "); /* * 2. Modify the order status to 4, indicating that the transaction is successful*/ orderDao.updateState(oid, 4); }} public class OrderServlet extends BaseServlet { private OrderService orderService = new OrderService(); /** * Pay to the bank* * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String zhiFu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Properties props = new Properties(); InputStream input = this.getClass().getClassLoader() .getResourceAsStream("merchantInfo.properties"); props.load(input); /* * Prepare 13 parameters*/ String p0_Cmd = "Buy"; String p1_MerId = props.getProperty("p1_MerId"); String p2_Order = request.getParameter("oid"); String p3_Amt = "0.01"; String p4_Cur = "CNY"; String p5_Pid = ""; String p6_Pcat = ""; String p7_Pdesc = ""; String p8_Url = props.getProperty("p8_Url"); String p9_SAF = ""; String pa_MP = ""; String pd_FrpId = request.getParameter("pd_FrpId"); String pr_NeedResponse = "1"; /* * Calculate hmac */ String keyValue = props.getProperty("keyValue"); String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, keyValue); /* * Connect the URL of Yibao and 13+1 parameters*/ StringBuilder url = new StringBuilder(props.getProperty("url")); url.append("?p0_Cmd=").append(p0_Cmd); url.append("&p1_MerId=").append(p1_MerId); url.append("&p2_Order=").append(p2_Order); url.append("&p3_Amt=").append(p3_Amt); url.append("&p4_Cur=").append(p4_Cur); url.append("&p5_Pid=").append(p5_Pid); url.append("&p6_Pcat=").append(p6_Pcat); url.append("&p7_Pdesc=").append(p7_Pdesc); url.append("&p8_Url=").append(p8_Url); url.append("&p9_SAF=").append(p9_SAF); url.append("&pa_MP=").append(pa_MP); url.append("&pd_FrpId=").append(pd_FrpId); url.append("&pr_NeedResponse=").append(pr_NeedResponse); url.append("&hmac=").append(hmac); System.out.println(url); /* * Redirect to Yibao*/ response.sendRedirect(url.toString()); return null; } /** * This method is the Yibao callback method. We must determine whether the Yibao is calling this method! * * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String back(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. Get 11 + 1 */ String p1_MerId = request.getParameter("p1_MerId"); String r0_Cmd = request.getParameter("r0_Cmd"); String r1_Code = request.getParameter("r1_Code"); String r2_TrxId = request.getParameter("r2_TrxId"); String r3_Amt = request.getParameter("r3_Amt"); String r4_Cur = request.getParameter("r4_Cur"); String r5_Pid = request.getParameter("r5_Pid"); String r6_Order = request.getParameter("r6_Order"); String r7_Uid = request.getParameter("r7_Uid"); String r8_MP = request.getParameter("r8_MP"); String r9_BType = request.getParameter("r9_BType"); String hmac = request.getParameter("hmac"); /* * 2. Verify whether the visitor is Yibao! */ Properties props = new Properties(); InputStream input = this.getClass().getClassLoader() .getResourceAsStream("merchantInfo.properties"); props.load(input); String keyValue = props.getProperty("keyValue"); boolean bool = PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd, r1_Code, r2_TrxId, r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid, r8_MP, r9_BType, keyValue); if(!bool) {//If the verification fails request.setAttribute("msg", "You are not a good thing!"); return "f:/jsps/msg.jsp"; } /* * 3. Get the status order, determine whether you want to modify the order status, and add points and other business operations*/ orderService.zhiFu(r6_Order);//It is possible to operate the database, or it may not operate! /* * 4. Determine the current callback method* If it is point-to-point, you need to feedback the string starting with success*/ if(r9_BType.equals("2")) { response.getWriter().print("success"); } /* * 5. Save the success information and forward it to msg.jsp */ request.setAttribute("msg", "Payment successful! Wait for the seller to ship! You wait~"); return "f:/jsps/msg.jsp"; } /** * Confirm the receipt* * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String confirm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. Get oid parameters 2. Call service method > If there is an exception, save the exception information and forward to msg.jsp 3. * Save the successful information and forward to msg.jsp */ String oid = request.getParameter("oid"); try { orderService.confirm(oid); request.setAttribute("msg", "Congratulations, the transaction is successful!"); } catch (OrderException e) { request.setAttribute("msg", e.getMessage()); } return "f:/jsps/msg.jsp"; } /** * Loading order* * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String load(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. Get oid parameter 2. Use oid to call the service method to get Order 3. * Save to the request domain and forward to /jsps/order/desc.jsp */ request.setAttribute("order", orderService.load(request.getParameter("oid"))); return "f:/jsps/order/desc.jsp"; } /** * My order* * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String myOrders(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. Get the current user from the session and then get its uid 2. * Use uid to call orderService#myOrders(uid) to get all orders of the user List<Order> 3. * Save the order list to the request field and forward to /jsps/order/list.jsp */ User user = (User) request.getSession().getAttribute("session_user"); List<Order> orderList = orderService.myOrders(user.getUid()); request.setAttribute("orderList", orderList); return "f:/jsps/order/list.jsp"; } /** * Add an order to use the car in the session to generate an Order object* * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 1. Get cart from session 2. Use cart to generate an Order object 3. Call the service method to complete the order 4. * Save order to the request field and forward to /jsps/order/desc.jsp */ // Get cart from session Cart cart = (Cart) request.getSession().getAttribute("cart"); // Convert cart to an Order object/* * Create an Order object and set the attribute * * Cart --> Order */ Order order = new Order(); order.setOid(CommonUtils.uuid()); // Set the number order.setOrdertime(new Date()); // Set order.setState(1);// Set the order status to 1, indicating that the payment is not paid User user = (User) request.getSession().getAttribute("session_user"); order.setOwner(user);// Set the order owner order.setTotal(cart.getTotal());// Set the order total and get the total from cart/* * Create an order entry collection* * cartItemList --> orderItemList */ List<OrderItem> orderItemList = new ArrayList<OrderItem>(); // Loop through all CartItems in Cart, use each CartItem object to create an OrderItem object, and add it to the collection for (CartItem cartItem : cart.getCartItems()) { OrderItem oi = new OrderItem();// Create an order entry oi.setIid(CommonUtils.uuid());// Set the id of the entry oi.setCount(cartItem.getCount());// Set the number of entries oi.setBook(cartItem.getBook());// Set the book oi.setSubtotal(cartItem.getSubtotal());// Set the subtotal of the entry oi.setOrder(order);// Set the order ItemList.add(oi);// Add the order entry to the collection} // Add all order entries to the order order.setOrderItemList(orderItemList); // Clear the shopping cart cart.clear(); // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// request.setAttribute("order", order); return "/jsps/order/desc.jsp"; }}2. Generate an order
3. My order (check by user)
4. Load the order (check by id)
5. Confirm the receipt
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.