JavaWeb10 (realize settlement & view order & order details)

Directory

1. Effect preview

2. Implementation ideas

2.1 Realize settlement

① Form an order and assign a value

② Insert the order into the data table tb_order, and at the same time insert the order item corresponding to the order into the data table tb_orderitem

2.2 View my order

① The underlying code

② Front-end binding value

2.3 View order details

① page jump, parameter passing

②The underlying code

③ Front-end binding value


One. Effect preview

2. Implementation idea

2.1 Realize billing

①Form an order and assign a value

//Get the shopping cart from the session
List items =(List)session.getAttribute(“mycart”);
//Get the user from the session
User user = (User)session. getAttribute(“user”);

//form an order
Order order = new Order();
//Assign a value to the order Missing oid! ! ! ! ! ! !
order.setItems(items);
order.calcSum();//Be sure to assign a value to the collection first
order. setUser(user);
order.setOaddress(user.getUaddress());

//Call the method of adding an order
int n = iob. addOrder(order);
if(n>0) {
// Indicates that the settlement is successful
session.setAttribute(“mycart”, null);
//Jump to my order page
resp.sendRedirect(“orders.do”);
}
else {
resp.sendRedirect(“cart.jsp?index=5”);
}

②Insert the order into the data table tb_order, and at the same time, insert the order item corresponding to the order The line item is inserted into the data table tb_orderitem

package com.zking.entity;
/**
 * Entity class order class
 * @author PC
 *
 */

import java.io.Serializable;
import java.util.List;

public class Order implements Serializable{
\t
/**
*
*/
private static final long serialVersionUID = 1L;
private int oid;//order number
private double osumprice;//order total price
private User user;//User object
private String oaddress;//order address

//An order is composed of multiple line items√
private List<OrderItem> items=null;
\t
//Calculate the total price of the order
public void calcSum() {
double sum = 0;
for (OrderItem oi : items) {
sum + =oi.getOiprice();//Accumulate the sum of subtotals
}
this.osumprice=sum;//calculate the total price again
}

public int getOid() {
return oid;
}

public void setOid(int oid) {
this.oid = oid;
}
\t

public double getOsumprice() {
return osumprice;
}

public void setOsumprice(double osumprice) {
this.osumprice = osumprice;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this. user = user;
}

public String getOaddress() {
return oaddress;
}

public void setOaddress(String oaddress) {
this. oaddress = oaddress;
}

public List<OrderItem> getItems() {
return items;
}

public void setItems(List<OrderItem> items) {
this.items = items;
}
\t
public Order() {
// TODO Auto-generated constructor stub
}

public Order(int oid, double osumprice, User user, String oaddress, List<OrderItem> items) {
this.oid = oid;
this.osumprice = osumprice;
this. user = user;
this. oaddress = oaddress;
this.items = items;
}
\t
public Order(double osumprice, User user, String oaddress, List<OrderItem> items) {
this.osumprice = osumprice;
this. user = user;
this. oaddress = oaddress;
this.items = items;
}

@Override
public String toString() {
return "Order [oid=" + oid + ", osumprice=" + osumprice + ", user=" + user + ", oaddress=" + oaddress
+ ", items=" + items + "]";
}
\t
\t
\t
\t
\t
}
package com.zking.entity;

import java.io.Serializable;
/**
 * Entity class: line item class
 * @author PC
 *
 */
public class OrderItem implements Serializable{
\t
private static final long serialVersionUID = 1L;
private int oiid;//line item number
private int oid;//order number
// private int gid;//product number
private Goods goods;//The commodity object can get all its data indirectly
private int oinum;//Purchase quantity
    private double oiprice;//subtotal
    
    public void calcxj() {
    // Subtotal = unit price * quantity
    this.oiprice=this.goods.getGprice()*this.oinum;
    String ss = String. format("%.1f",oiprice);
    double s = Double. parseDouble(ss);
    this.oiprice=s;
    }
    
public int getOiid() {
return oiid;
}
public void setOiid(int oiid) {
this.oiid = oiid;
}
public int getOid() {
return oid;
}
public void setOid(int oid) {
this.oid = oid;
}
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
public int getOinum() {
return oinum;
}
public void setOinum(int oinum) {
this.oinum = oinum;
}
public double getOiprice() {
return oiprice;
}
public void setOiprice(double oiprice) {
this.oiprice = oiprice;
}
    
    public OrderItem() {
// TODO Auto-generated constructor stub
}
public OrderItem(int oid, int oid, Goods goods, int oinum, double oiprice) {
this.oiid = oiid;
this.oid = oid;
this.goods = goods;
this.oinum = oinum;
this.oiprice = oiprice;
}
    
public OrderItem(int oid, Goods goods, int oinum, double oiprice) {
this.oid = oid;
this.goods = goods;
this.oinum = oinum;
this.oiprice = oiprice;
}
@Override
public String toString() {
return "OrderItem [oiid=" + oiid + ", oid=" + oid + ", goods=" + goods + ", oinum=" + oinum + ", oiprice="
+ oiprice + "]";
}
   
    
}
package com.zking.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.zking.entity.Order;
import com.zking.entity.OrderItem;
import com.zking.entity.User;
import com.zking.util.DBHelper;

/**
 * Data access layer tb_order
 * @author PC
 *
 */
public class OrderDao implements IOrderDao {

private Connection con = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
boolean flag;
/**
* According to the user to get the order
* @param u user object
* @return order collection
*/
public List<Order> getAllByUser(User u){
List<Order> ls = new ArrayList<Order>();
try {
con = DBHelper. getCon();
String sql="select * from (select * from tb_order order by oid desc) where uuid=" + u.getUuid();
ps=con. prepareStatement(sql);
rs=ps. executeQuery();
while(rs. next()) {
Order o = new Order();
o.setOid(rs.getInt(1));
String ss = String.format("%.1f",rs.getDouble(2));
double s = Double. parseDouble(ss);
o. setOsumprice(s);
o. setUser(u);
o.setOaddress(rs.getString(4));
ls. add(o);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.myClose(con, ps, rs);
}
return ls;
\t\t
}
\t
/**
* single query
* @param oid
* @return
*/
public Order getOrder(String oid) {
Order o = new Order();
OrderItemDao odd = new OrderItemDao();
try {
con = DBHelper. getCon();
String sql="select * from tb_orderitem where oid=" + oid;
ps=con. prepareStatement(sql);
rs=ps. executeQuery();
if(rs. next()) {
o.setOid(rs.getInt(1));
o.setOsumprice(rs.getDouble(2));
o.setOaddress(rs.getString(4));
//Get the line item collection corresponding to the order
List<OrderItem> items = odd. getAllByOid(oid);
o. setItems(items);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.myClose(con, ps, rs);
}
return o;
}
\t
\t
\t
\t
/**
* Increase order
* @param order order object
* @return Affected row count
*/
public int addOrder(Order order) {
int n = 0;
int oid = getID("tb_order", "oid");///!!! Assignment order number
OrderItemDao odao = new OrderItemDao();
try {
con = DBHelper. getCon();
String sql="insert into tb_order(oid,osumprice,uuid,oaddress) values(?,?,?,?)";
ps=con. prepareStatement(sql);
// assign value to placeholder
ps.setInt(1, oid);
ps.setDouble(2, order.getOsumprice());
ps.setInt(3, order.getUser().getUuid());
ps.setString(4, order.getOaddress());
n=ps.executeUpdate();
if(n>0) {//Indicates that the order was placed successfully
//Then add all the line items corresponding to the order to the database
//Get the line item collection corresponding to the order
List<OrderItem> items = order. getItems();
//Loop through
for (OrderItem oi : items) {
//Next I need to put all the oi into the tb_orderitem table
oi.setOid(oid);//Key
odao.addOrderItem(oi);
//Put the corresponding product sales + purchase quantity inventory - purchase quantity
new GoodsDao(). updateXL(oi. getGoods(). getGid(), oi. getOinum());
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.myClose(con, ps, rs);
}
\t\t
return n;
}
\t
/**
* delete order
* @param oid
* @return
*/
public boolean deleteOrderByOid(int oid) {
try {
con = DBHelper. getCon();
String sql="delete from tb_order where oid=" + oid;
ps=con. prepareStatement(sql);
if(ps. executeUpdate()>0) {
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.myClose(con, ps, rs);
}
return flag;
}

\t
/**
* Realization of the identity column ② Take the maximum serial number of the table + 1
* @param tabName table name
* @param colName column name
* @return
*/
public int getID(String tabName,String colName) {//table name column name
int n = 0;
try {
con = DBHelper. getCon();
String sql="select nvl(max(" + colName + "),0) + 1 from " + tabName;
ps=con. prepareStatement(sql);
rs=ps. executeQuery();
if(rs. next()) {
n=rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBHelper.myClose(con, ps, rs);
}
return n;
\t\t
}


\t


\t


\t
}

2.2 View my order

①Underlying code

package com.zking.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zking.biz.GoodsBiz;
import com.zking.biz.IGoodsBiz;
import com.zking.biz.IOrderBiz;
import com.zking.biz.IUserBiz;
import com.zking.biz.OrderBiz;
import com.zking.biz.UserBiz;
import com.zking.entity.Goods;
import com.zking.entity.Order;
import com.zking.entity.User;

/**
 * Orders Controller Multiple Orders
 * @author PC
 *
 */
@WebServlet("/orders.do")
public class OrdersServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
\t
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Set encoding
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html; charset=UTF-8");
\t
//Take session and out
HttpSession session = req. getSession();
PrintWriter out = resp. getWriter();
\t\t
//Get the user from the session
User u =(User)session.getAttribute("user");
\t
//servlet calls biz
IOrderBiz iob = new OrderBiz();
//Call the method to get the order collection
\t\t
List<Order> ordersls = iob. getAllByUser(u);
\t\t//save
req.setAttribute("ordersls", ordersls);
\t
//Forward to myorder.jsp for binding value
req.getRequestDispatcher("myorder.jsp?index=6").forward(req, resp);
\t
\t
}
}

②Front-end binding value

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">

<head>
   <title>My order</title>
    <!-- Support mobile terminal -->
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <!-- Import CSS -->
    <link rel="stylesheet" href="CSS/bootstrap.css" />
    <!-- Introduce the style of Bootstrap icon -->
    <link rel="stylesheet" href="font/bootstrap-icons.css" />
    <style>
        .navbar-collapse {
            /*1 means elastic expansion occupies the rest of the parent container, 0 means not occupied*/
            flex-grow: 0;
        }

        .active {
              /*Bold*/
            font-weight: bold;
        }
        .text-right button{
                width: 120px;/*width*/
                height: 30px;/*height*/
                line-height: 10px; /*line height*/
                margin-top: 10px; /*top spacing*/
        }
    </style>
</head>

<body>
\t
<!--The page contains -->
   <jsp:include page="header.jsp"></jsp:include>

   

    <!-- My Orders -->
    <div class="container">
    \t
    <!--When the order collection is empty -->
      <c:if test="${empty ordersls}">
      <div style="margin-top: 50px;margin-bottom:50px" class="h3 text-center text-pink">Dear ${user.uname}, the order is empty<a href=\ "index.do?index=1">Go and reward yourself! </a></div>
     <div class="text-center">
     <img width="700px" src="img/bz11.jpg">
     </div>
      </c:if>
      
      <!--When the order collection is not empty -->
      <c:if test="${not empty ordersls}">
    <!-- text-center centered -->
        <table style="margin-top: 20px;" class="table table-hover text-center">
            <!-- class="bg-primary" add color -->
            <thead class="bg-primary" style="color: aliceblue;">
                <tr>
                    <th scope="col">Order Number</th>
                    <th scope="col">Shipping Address</th>
                    <th scope="col">Order Total Price</th>
                    <th scope="col">Buyer</th>
                    <th scope="col">Operation</th>
                </tr>
            </thead>
            <tbody>
            
              <!--The value of the binding order -->
             <c:forEach items="${ordersls}" var="o">
             <tr style="height:80px;line-height: 50px">
                    <th scope="row">${o.oid}</th>
                    <td>${o.oaddress}</td>
                    <td>${o.osumprice} &yen;</td>
                    <td>${o.user.uname}</td>
                    <td>
                    <a href="deleteOrder.do?oid=${o.oid}" onclick="return confirm('Are you sure to delete?(^.^)')" >Delete order</a> &nbsp; &nbsp; &nbsp;
                    <a href="orderInfo.do?oid=${o.oid}">View order details</a>
                    </td>
                </tr>
             </c:forEach>
            
            </tbody>
            </table>

      </c:if>
    
       
    </div>

    <!-- Import jQuery class library -->
    <!-- Reintroduce the Bootstrap class library -->
    <script src="js/jquery-3.6.4.js"></script>
    <script src="js/bootstrap.js"></script>
    
    
</body>

</html>

2.3 View order details

①Page jump, pass parameters

//Jump Forward to the order details page for binding
req.getRequestDispatcher(“orderinfo.jsp”).forward(req, resp);

②Underlying code

package com.zking.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zking.biz.IOrderBiz;
import com.zking.biz.IUserBiz;
import com.zking.biz.OrderBiz;
import com.zking.biz.UserBiz;
import com.zking.entity.Order;
import com.zking.entity.User;

/**
 * View order details controller
 * @author PC
 *
 */
@WebServlet("/orderInfo.do")
public class OrderInfoServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
\t
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//Set encoding
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html; charset=UTF-8");
\t
//Take session and out
HttpSession session = req. getSession();
PrintWriter out = resp. getWriter();
\t\t
//receive oid
String oid=req. getParameter("oid");
\t\t
//servlet adjust biz layer
IOrderBiz iob = new OrderBiz();
// method to call a single query
Order order = iob. getOrder(oid);
\t\t//save
req.setAttribute("myorder",order);//key value
//Jump Forward to the order details page for binding
req.getRequestDispatcher("orderinfo.jsp").forward(req, resp);
\t\t
\t\t
//Two ways of thinking
/**
* select * from tb_orderitem where oid=?;
* 1. Find the corresponding order item set according to the order number, save it, and go to the order details page to bind the value
*
* select * from tb_order where oid=?; single query writes an items in the order entity class
* 2. Find the corresponding order according to the order number, save the order, go to the order details interface, you can bind the value of the order and the value of the order details √
*
*
*/
\t
\t
}
}

③Front-end binding value

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en">

<head>
   <title>View order details</title>
    <!-- Support mobile terminal -->
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <!-- Import CSS -->
    <link rel="stylesheet" href="CSS/bootstrap.css" />
    <!-- Introduce the style of Bootstrap icon -->
    <link rel="stylesheet" href="font/bootstrap-icons.css" />
    <style>
        .navbar-collapse {
            /*1 means elastic expansion occupies the rest of the parent container, 0 means not occupied*/
            flex-grow: 0;
        }

        .active {
              /*Bold*/
            font-weight: bold;
        }
        .text-right button{
                width: 120px;/*width*/
                height: 30px;/*height*/
                line-height: 10px; /*line height*/
                margin-top: 10px; /*top spacing*/
        }
    </style>
</head>

<body>
\t 

    <!-- Order Details -->
    <div class="container" style="margin-top: 40px">
    
    <!--When the order is empty -->
      <c:if test="${empty myorder}">
      <jsp:forward page="orders.do?index=6"></jsp:forward>
      </c:if>
      
      <!--When the shopping cart collection is not empty -->
      <c:if test="${not empty myorder}">
    <!-- text-center centered -->
        <table style="margin-top: 20px;" class="table table-hover text-center">
            <!-- class="bg-primary" add color -->
            <thead class="bg-primary" style="color: aliceblue;">
                <tr>
                    <th scope="col">Line Item ID</th>
                    <th scope="col">Order Number</th>
                    <th scope="col">Product Name</th>
                    <th scope="col">Product Price</th>
                    <th scope="col">Product image</th>
                    <th scope="col">Purchase Quantity</th>
                    <th scope="col">Subtotal</th>
                </tr>
            </thead>
            <tbody>
            
            <!--Objects cannot be traversed by themselves, foreach is consistent with entity classes -->
              <!--Bind the value of the corresponding line item -->
             <c:forEach items="${myorder.items}" var="oi">
             <tr style="height:80px;line-height: 50px">
                    <th scope="row">${oi.oiid}</th>
                    <td>${oi.oid}</td>
                    <td>${oi.goods.gname}</td>
                    <td>${oi.goods.gprice}$</td>
                    <td><img width="80px" src="${oi.goods.gpath}"></td>
                    <td>${oi.oinum}</td>
                    <td><span class="xx">${oi.oiprice}</span>yuan</td>
                </tr>
             </c:forEach>
            </tbody>
            </table>

        <!-- Total -->
        <div class="text-right">
            <h2>Total: <span id="sums">229.3</span>yuan</h2>
           <a href="orders.do?index=6"> <button type="button" class="btn btn-success" >Click back</button></a>
        </div>
      </c:if>
    
    </div>

    <!-- Import jQuery class library -->
    <!-- Reintroduce the Bootstrap class library -->
    <script src="js/jquery-3.6.4.js"></script>
    <script src="js/bootstrap.js"></script>
    
    <script type="text/javascript">
    //load DOM jquery
$(function(){
// Statistical price
var sum = 0.0;
// traverse
$(".xx").each(function(i,v){//subscript value
//Cumulative sum
sum + =parseFloat(v. innerHTML);
});
//keep 1 decimal place
sum = sum.toFixed(2);
//Assign a value to the span tag
$("#sums").html(sum);
})
    
    //If you want to get the id, set the id directly to gid
    function myf(gid) {
//Get the number of text boxes
var num=$("#" + gid).val();
//jump to servlet
location.href="updateCart.do?gid=" + gid + " & amp;num=" + num;
}
/* //If there are still many decimal places, use the following method to keep 1 decimal place
    String s = String.format("%.1f",this.oiprice);
    this.oiprice=Double.parseDouble(s); */
    \t
\t\t
    \t
    </script>
</body>

</html>