简体   繁体   中英

Insert Multiple row into database mysql from jsp

There are a few rows that would be generated from my database and shown in my jsp page. I have put 1 submit button and once the user clicks the submit button, I want to insert the data shown in the jsp page to the MySQL table. I have searched for the answer in this forum and try to follow some of the solution given but I get this error: java.lang.ArrayIndexOutOfBoundsException: 1 and when I search for the error it brings me to the Controller at po.setAddress(address[i]);

           po = new PaidOrder();
           po.setId(pid[i]);
           po.setPname(pname[i]);
           po.setQuantity(quantity[i]);
           po.setPrice(price[i]);
           po.setStatus(status[i]);
           po.setAddress(address[i]);
           po.setUser_email(user_email[i]); 

Below are the full code :

JSP

<form action="PaidOrderController" method="post">
<table class="timetable_sub">
   <thead>
       <tr>
          <th>Product Name</th>
          <th>Quantity</th>
          <th>Price</th>
          <th>Total Price</th>
          <th>Action</th>
        </tr>
    </thead>
    <tbody>
    <%
        OrderDAO dao = new OrderDAO();
        List<Order> orderList = dao.getAllOrderByEmail(user);
        DecimalFormat df = new DecimalFormat("#0.00");
        for (Order o : orderList) {
     %>
        <tr class="rem1">
          <td class="invert"><%= o.getPname() %></td>
          <td class="invert"><%= o.getQuantity() %></td>
          <td class="invert">RM <%= df.format(o.getPrice()) %></td>
          <td class="invert">RM <%= df.format(o.getQuantity()*o.getPrice()) %></td>
          <td>
              <a href="EditCartController?action=edit&id=<%= o.getId()%>"><button type="button" class="btn btn-success">Edit</button></a>
              <a href="DeleteFromCartController?action=delete&id=<%= o.getId()%>"><button type="button" class="btn btn-danger">Delete</button></a>
          </td>
          <input type="hidden" name="id" value="<%= o.getId() %>">
          <input type="hidden" name="pname" value="<%= o.getPname() %>">
          <input type="hidden" name="quantity" value="<%= o.getQuantity() %>">
          <input type="hidden" name="price" value="<%= o.getQuantity()*o.getPrice() %>">
          <input type="hidden" name="status" value="paid">
          <input type="hidden" name="user_email" value="<%=user%>">
       </tr>
          <%
             }
          %>
<div class="form-group" style="margin-top:20px">
    <label for="exampleFormControlTextarea1">Please fill up your address for postage below:</label>
    <textarea class="form-control" name="address" rows="3"></textarea>
</div>
<div class="checkout-right-basket">
    <button type="submit">Make a Payment<span class="far fa-hand-point-right"></span></button>
</div>
</form>

Code in PaidOrder Model

public class PaidOrder {
    private String id;
    private String pname;
    private String quantity;
    private String price;
    private String status;
    private String address;
    private String user_email;

    public void setId(String id) {
        this.id = id;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public void setQuantity(String quantity) {
        this.quantity = quantity;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void setUser_email(String user_email) {
        this.user_email = user_email;
    }

    public String getId() {
        return id;
    }

    public String getPname() {
        return pname;
    }

    public String getQuantity() {
        return quantity;
    }

    public String getPrice() {
        return price;
    }

    public String getStatus() {
        return status;
    }

    public String getAddress() {
        return address;
    }

    public String getUser_email() {
        return user_email;
    }

}

PaidOrderController

@WebServlet(name = "PaidOrderController", urlPatterns = {"/PaidOrderController"})
public class PaidOrderController extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PaidOrder po;
        List<PaidOrder> listPaidOrder= new ArrayList<>();

        String[] pid = request.getParameterValues("id");
        String[] pname = request.getParameterValues("pname");
        String[] quantity = request.getParameterValues("quantity");
        String[] price = request.getParameterValues("price");
        String[] status = request.getParameterValues("status");
        String[] user_email = request.getParameterValues("user_email");

        for(int i = 0; i < pid.length; i++){
            po = new PaidOrder();
            po.setId(pid[i]);
            po.setPname(pname[i]);
            po.setQuantity(quantity[i]);
            po.setPrice(price[i]);
            po.setStatus(status[i]);
            po.setUser_email(user_email[i]);

            listPaidOrder.add(po);

        }

        PaidOrderDAO.paidOrder(listPaidOrder);
    }

PaidOrderDAO

public static void paidOrder(List<PaidOrder> listPaidOrder){
        try(Connection conn = DBConnectionUtil.getConnection()) {

           String sql="INSERT INTO paid_orders(pname,quantity,price,status,user_email) VALUES (?,?,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql); 

            for(PaidOrder o:listPaidOrder){
                ps.setString(1, o.getPname());
                ps.setString(2, o.getQuantity());
                ps.setString(3, o.getPrice());
                ps.setString(4, o.getStatus());
                ps.setString(5, o.getUser_email());
                ps.executeUpdate();
            }

         } catch (Exception e){
            System.out.println("OrderDAO error"+ e.getMessage());
        }
    }

I hope someone can help me to solve this :(

The error you are getting is from po.setAddress(address[i]); because you have just one address in the form. Remove it from the for loops and it will solve your problem.

You will need to change the implementation of processRequest and paidOrder in order to save the address eg the implementation of processRequest can be changed as

@WebServlet(name = "PaidOrderController", urlPatterns = {"/PaidOrderController"})
public class PaidOrderController extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PaidOrder po;
        List<PaidOrder> listPaidOrder= new ArrayList<>();

        String[] pid = request.getParameterValues("id");
        String[] pname = request.getParameterValues("pname");
        String[] quantity = request.getParameterValues("quantity");
        String[] price = request.getParameterValues("price");
        String[] status = request.getParameterValues("status");
        String[] user_email = request.getParameterValues("user_email");

        String address = request.getParameter("address");           

        for(int i = 0; i < pid.length; i++){
            po = new PaidOrder();
            po.setId(pid[i]);
            po.setPname(pname[i]);
            po.setQuantity(quantity[i]);
            po.setPrice(price[i]);
            po.setStatus(status[i]);                
            po.setUser_email(user_email[i]);

            listPaidOrder.add(po);
        }

        PaidOrderDAO.paidOrder(listPaidOrder, address);
    }
}

Accordingly, the implementation of paidOrder will have to be changed as:

public static void paidOrder(List<PaidOrder> listPaidOrder, String address){
    try(Connection conn = DBConnectionUtil.getConnection()) {

       String sql="INSERT INTO paid_orders(pname,quantity,price,status,user_email,address) VALUES (?,?,?,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql); 

        for(PaidOrder o:listPaidOrder){
            ps.setString(1, o.getPname());
            ps.setString(2, o.getQuantity());
            ps.setString(3, o.getPrice());
            ps.setString(4, o.getStatus());
            ps.setString(5, o.getUser_email());
            ps.setString(6, address);            
            ps.executeUpdate();
        }

     } catch (Exception e){
        System.out.println("OrderDAO error"+ e.getMessage());
    }
}

Feel free to comment if you need any further help regarding this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM