简体   繁体   中英

capture the wrong id for the checkbox [struts 1.3.8 Always capture the first ID]

I am using struts 1.3.8 with netbeans 6.9 and I want to update the cart information in my application but when I check the checkbox for any item in the cart, it deletethe first row in the table cart and I don't know why it is not taking the correct cartID to delete or edit or check out.

the jsp page:

<body>
    <h1>Customer Cart</h1><h6><p align="left"><a href="logout">logout</a></p></h6>
    <!-- include the DB connection -->
    <%@ include file="DBconnection.jsp" %>

    <% String userID = (String) session.getAttribute("userID");
                String categoryID = (String) session.getAttribute("categoryID");
                String brandID = (String) session.getAttribute("brandID");

                System.out.println(userID);%>

    <!-- retrive the brands from DB to populate the select box -->
    <% String QueryString = "select cart.cartID, cart.itemID, cart.Qyt, item.itemName, item.itemPrice from cart , item where cart.itemID = item.itemID and customerID=" + userID + ";";
    %>

    <html:form action="/updateCart">

        <table border="0">
            <thead>
                <tr>
                    <td colspan="5">
                        <span style='color:red'>
                            <i><html:errors property="checkbox" /></i>
                            <i><html:errors property="cartQyt" /></i>
                        </span>
                    </td>
                </tr>
                <tr>
                    <th></th>
                    <th>Item Name</th>
                    <th>Item Price</th>
                    <th>Qyantity</th>
                </tr>
            </thead>
            <tbody>

                <%
                            try {
                                rs = stmt.executeQuery(QueryString);
                                while (rs.next()) {
                                    int cartID = rs.getInt("cartID");
                                    int cartItemID = rs.getInt("itemID");
                                    String itemName = rs.getString("itemName");
                                    int itemPrice = rs.getInt("itemPrice");
                                    int Qyt = rs.getInt("Qyt");
                %>
                <tr>
                    <td><input type="checkbox" name="checkbox" value="<%=cartID%>"/></td>
                    <td><%=itemName%></td>
                    <td><%=itemPrice%></td>
                    <td><input type="text" name="cartQyt" value="<%=Qyt%>" /></td>

                    <td colspan="4">
                        <input type="hidden" name="cartItemID" value="<%=cartItemID%>"/>
                        <input type="hidden" name="cartUserID" value="<%=userID%>"/>
                        <input type="hidden" name="cartItemPrice" value="<%=itemPrice%>"/>
                        <html:submit property="cartButton" value="Edit"/>
                        <html:submit property="cartButton" value="Delete"/>
                        <html:submit property="cartButton" value="Check out"/>
                        <%
                                                                    }

                                } catch (Exception e) {
                                    System.out.println("retrieve from DB:" + e);
                                }
                    %>
                    </td>
                </tr>
                <tr>
                    <td>

                    </td>
                    <td>
                    <a href="userHome.jsp"><input type="button" name="back" value="back  to home"/></a>
                    </td>
                </tr>

            </tbody>
        </table>


    </html:form>

</body>

the formBean:

public class AddToCartForm extends org.apache.struts.action.ActionForm {

private int Qyt;
private int itemID;
private int itemQyt;
private int number;
private int cartUserID;
private int cartItemID;
private int cartItemPrice;
private int cartQyt;
private String cartItemName;
private int cartID;
private String cartButton;
private String checkbox;

public String getCartButton() {
    return cartButton;
}

public void setCartButton(String cartButton) {
    this.cartButton = cartButton;
}

public String getCheckbox() {
    return checkbox;
}

public void setCheckbox(String checkbox) {
    this.checkbox = checkbox;
}

public int getCartID() {
    return cartID;
}

public void setCartID(int cartID) {
    this.cartID = cartID;
}


public int getCartItemID() {
    return cartItemID;
}

public void setCartItemID(int cartItemID) {
    this.cartItemID = cartItemID;
}

public String getCartItemName() {
    return cartItemName;
}

public void setCartItemName(String cartItemName) {
    this.cartItemName = cartItemName;
}

public int getCartItemPrice() {
    return cartItemPrice;
}

public void setCartItemPrice(int cartItemPrice) {
    this.cartItemPrice = cartItemPrice;
}

public int getCartQyt() {
    return cartQyt;
}

public void setCartQyt(int cartQyt) {
    this.cartQyt = cartQyt;
}

public int getCartUserID() {
    return cartUserID;
}

public void setCartUserID(int cartUserID) {
    this.cartUserID = cartUserID;
}

public int getItemQyt() {
    return itemQyt;
}

public void setItemQyt(int itemQyt) {
    this.itemQyt = itemQyt;
}

public int getItemID() {
    return itemID;
}

public void setItemID(int itemID) {
    this.itemID = itemID;
}




/**
 * @return
 */
public int getQyt() {
    return Qyt;
}

/**
 * @param string
 */
public void setQyt(int Qyt) {
    this.Qyt = Qyt;
}

/**
 * @return
 */
public int getNumber() {
    return number;
}

/**
 * @param i
 */
public void setNumber(int number) {
    this.number = number;
}

/**
 *
 */
public AddToCartForm() {
    super();
    // TODO Auto-generated constructor stub
}

the action:

public class updateCartAction extends org.apache.struts.action.Action {

/* forward name="success" path="" */
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
// Initialize SQL connection equal null
private Connection con = null;
private ResultSet rs = null;
private Statement stmt = null;

/**
 * This is the action called from the Struts framework.
 * @param mapping The ActionMapping used to select this instance.
 * @param form The optional ActionForm bean for this request.
 * @param request The HTTP Request we are processing.
 * @param response The HTTP Response we are processing.
 * @throws java.lang.Exception
 * @return
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //Initilized Action error
    ActionErrors errors = new ActionErrors();
    // set the session on
    HttpSession session = request.getSession(true);
    //Call AddToCartForm Instance here
    AddToCartForm formBean = (AddToCartForm) form;
    // define newQuantity and itemID and orderStatus and Qyt and itemPrice and customerID
    int newQuantity = 0;

    String orderStatus = "Open";
    //Initilize Date today = new Date();
    java.util.Date now = new java.util.Date();
    String DATE_FORMAT = "yyyy-MM-dd";
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
    String strDateNew = sdf.format(now);
    // extract user data
    //Integer cartUserID = formBean.getCartUserID();
    Integer checkbox = formBean.getCartID();
    Integer cartItemID = formBean.getCartItemID();
    Integer cartQyt = formBean.getCartQyt();
    String cartButton = formBean.getCartButton();
    Integer cartItemPrice = formBean.getCartItemPrice();
    Integer userID = Integer.parseInt(session.getAttribute("userID").toString());

    // check user data
    System.out.println("cart User whose ID is : " + userID + " want to " + cartButton + " the cart its ID is : " + cartItemID + " that contains the item its ID is : " + cartItemID + " with the Qyt :" + cartQyt);

    //Set up flag message
    boolean flag = false;

    // perform validation
    if ((checkbox == 0) || // checkbox parameter does not exist
        (checkbox < 1)){   // the user did not select any checkbox
        errors.add("checkbox", new ActionMessage("errors.checkbox.required"));
    }
    // perform validation
    if ((cartQyt == 0) ||  // cartQyt parameter does not exist
        (cartQyt < 1)){    // cartQyt parameter is empty
        errors.add("cartQyt", new ActionMessage("errors.cartQyt.required"));
    }
    //Save error messages keys into the appropriate HTTP request attribute for use by the <html:errors> tag
    saveErrors(request, errors);
    //Check- is errors empty
    if (errors.isEmpty()) {
        flag = true;
    } else {
        flag = false;
    }
    if (flag == true) {

        // start updateCartAction
        System.out.println("////////////////////////// Start updateCartAction /////////////////////////");
        // Now Start communicate with database
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/gsm", "root", "root");


            if (cartButton.equals("Delete")){    //// if the user select delete button

                try{

                    // delete from cart
                    PreparedStatement ps = (PreparedStatement) con.prepareStatement("DELETE FROM cart where cartID=?");
                    ps.setInt(1, checkbox);
                    //Execute all the above statement
                    ps.execute();
                    //Check which cartID was deleted
                    System.out.println("Deleted from cart table, the cartID: " + checkbox);

                } catch (Exception e) {
                    errors.add("SQLDeletingCart", new ActionMessage("errors.SQLDeletingCart"));
                    System.out.println("ERROR Deleting : Did not delete cart info from the cart : " + e);
                }

                //Save error messages keys into the appropriate HTTP request attribute for use by the <html:errors> tag
                saveErrors(request, errors);
                //Check- is errors empty
                if (errors.isEmpty()) {
                    flag = true;
                } else {
                    flag = false;
                }

            }else if (cartButton.equals("Edit")){ //// if the user select edit button

                try{

                    // update the cart Qyt
                    PreparedStatement ps = (PreparedStatement) con.prepareStatement("UPDATE cart  SET Qyt=? where cartID=?");
                    ps.setInt(1, cartQyt);
                    ps.setInt(2, checkbox);
                    //Execute all the above statement
                    ps.execute();
                    flag = true;
                    //Check which cartID was deleted
                    System.out.println("Updated the quantity in the cart: "  + cartQyt + " for the cartID: " + checkbox);

                    } catch (Exception e) {
                        errors.add("SQLUpdatingCart", new ActionMessage("errors.SQLUpdating"));
                        System.out.println("ERROR Updating : Did not update the Qyt in the cart : " + e);
                    }

                    //Save error messages keys into the appropriate HTTP request attribute for use by the <html:errors> tag
                    saveErrors(request, errors);
                    //Check- is errors empty
                    if (errors.isEmpty()) {
                        flag = true;
                    } else {
                        flag = false;
                        String UserID = (String)session.getAttribute("userID");
                        session.setAttribute("userID", UserID);
                        return mapping.findForward(FAILURE);
                    }

            }else if (cartButton.equals("Check out")){ //// if the user select check out button

                    try{

                        try{

                            // get the cart and item info
                            PreparedStatement ps1 = (PreparedStatement) con.prepareStatement("select cart.itemID, cart.customerID, cart.Qyt, item.itemQyt, item.itemPrice from cart, item where cart.itemID=item.itemID and cart.cartID=?");
                            ps1.setInt(1, checkbox);
                            rs = ps1.executeQuery();

                            if (rs.next()) // Succes
                            {
                                flag = true;
                                int itemID = rs.getInt("itemID");
                                int customerID = rs.getInt("customerID");
                                int Qyt = rs.getInt("Qyt");
                                int itemQyt = rs.getInt("itemQyt");
                                int itemPrice = rs.getInt("itemPrice");
                                //new quantity
                                newQuantity = itemQyt - Qyt;
                                ///// check the data
                                System.out.println("The Item ID in the cart is: " + itemID + " and its price is : " + itemPrice + " for the customer whose ID is : " + customerID + " and the quantity selected is : " + Qyt + " from the total Qyt which is: " + itemQyt + " and the new Qyt for the item is : " + newQuantity);

                            }

                            flag = false;

                        } catch (Exception e) {
                            errors.add("SQLSelectingCartInfo", new ActionMessage("errors.SQLSelectingCartInfo"));
                            System.out.println("ERROR Selecting : Did not get the cart and item info : " + e);
                        }

                        //Save error messages keys into the appropriate HTTP request attribute for use by the <html:errors> tag
                        saveErrors(request, errors);
                        //Check- is errors empty
                        if (errors.isEmpty()) {
                            flag = true;
                        } else {
                            flag = false;
                            String UserID = (String)session.getAttribute("userID");
                            session.setAttribute("userID", UserID);
                            return mapping.findForward(FAILURE);
                        }

                        try{

                            // update the item Qyt in the item table after checking it out
                            PreparedStatement ps2 = (PreparedStatement) con.prepareStatement("UPDATE item SET itemQyt=? WHERE itemID=?");
                            ps2.setInt(1, newQuantity);
                            ps2.setInt(2, cartItemID);
                            int updateRows = ps2.executeUpdate();
                            ps2.close();

                        } catch (Exception e) {
                            errors.add("SQLUpdatingItem", new ActionMessage("errors.SQLUpdatingItem"));
                            System.out.println("ERROR Updating : Did not Update the itemQyt in the item table which the itemId is : " + cartItemID + " and the new Qyt is :" + newQuantity + " " + e);
                        }

                        //Save error messages keys into the appropriate HTTP request attribute for use by the <html:errors> tag
                        saveErrors(request, errors);
                        //Check- is errors empty
                        if (errors.isEmpty()) {
                            flag = true;
                        } else {
                            flag = false;
                            String UserID = (String)session.getAttribute("userID");
                            session.setAttribute("userID", UserID);
                            return mapping.findForward(FAILURE);
                        }

                        try{
                            // insert the cart info in the order table
                            PreparedStatement ps3 = (PreparedStatement) con.prepareStatement("INSERT INTO customerOrder(oderStatus, OrderDate, orderQyt, orderTotalPrice, customerID, itemID)"
                                + " VALUES (?,?,?,?,?,?) ");
                            ps3.setString(1, orderStatus);
                            ps3.setString(2, strDateNew);
                            ps3.setInt(3, cartQyt);
                            ps3.setInt(4, cartItemPrice);
                            ps3.setInt(5, userID);
                            ps3.setInt(6, cartItemID);

                            ///// check the data
                            System.out.println("The customer whose ID is: " + userID + " and his ordered item ID : " + cartItemID + " with price = " + cartItemPrice + " and quantity = " + cartQyt + " on that fate : " + strDateNew + " and the order status is : " + orderStatus);

                        } catch (Exception e) {
                            errors.add("SQLInsertingOrder", new ActionMessage("errors.SQLInsertingOrder"));
                            System.out.println("ERROR Inserting : Did not insert the info in the order : " + e);
                        }

                        //Save error messages keys into the appropriate HTTP request attribute for use by the <html:errors> tag
                        saveErrors(request, errors);
                        //Check- is errors empty
                        if (errors.isEmpty()) {
                            flag = true;
                        } else {
                            flag = false;
                            String UserID = (String)session.getAttribute("userID");
                            session.setAttribute("userID", UserID);
                            return mapping.findForward(FAILURE);
                        }

                        try{

                            // delete from cart table after check it out
                            PreparedStatement ps = (PreparedStatement) con.prepareStatement("DELETE FROM cart where cartID=?");
                            ps.setInt(1, checkbox);
                            //Execute all the above statement
                            ps.execute();

                        } catch (Exception e) {
                            errors.add("SQLDeletingCart", new ActionMessage("errors.SQLDeletingCart"));
                            System.out.println("ERROR Deleting from cart : Did not delete the order from the cart : " + e);
                        }

                        //Save error messages keys into the appropriate HTTP request attribute for use by the <html:errors> tag
                        saveErrors(request, errors);
                        //Check- is errors empty
                        if (errors.isEmpty()) {
                            flag = true;
                        } else {
                            flag = false;
                            String UserID = (String)session.getAttribute("userID");
                            session.setAttribute("userID", UserID);
                            return mapping.findForward(FAILURE);
                        }

                    }catch(Exception e){
                        System.out.println("ERROR : " + e);
                    }

                    //Save error messages keys into the appropriate HTTP request attribute for use by the <html:errors> tag
                    saveErrors(request, errors);
                    //Check- is errors empty
                    if (errors.isEmpty()) {
                        flag = true;
                    } else {
                        flag = false;
                        String UserID = (String)session.getAttribute("userID");
                        session.setAttribute("userID", UserID);
                        return mapping.findForward(FAILURE);
                    }
            }

        }catch (Exception ex) {
            errors.add("SQLException", new ActionMessage("errors.SQLException"));
            throw new SQLException(ex.fillInStackTrace());
        }

        //Close SQL server connection
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            throw new SQLException(e.getSQLState() + e.fillInStackTrace());
        }

        //Save error messages keys into the appropriate HTTP request attribute for use by the <html:errors> tag
        saveErrors(request, errors);
        //Check- is errors empty
        if (errors.isEmpty()) {
            flag = true;
        } else {
            flag = false;
        }

        if(flag) {
            String UserID = (String)session.getAttribute("userID");
            session.setAttribute("userID", UserID);
            return mapping.findForward(SUCCESS);
        }else {
            String UserID = (String)session.getAttribute("userID");
            session.setAttribute("userID", UserID);
            return mapping.findForward(FAILURE);
        }

    }

    return mapping.findForward(FAILURE);
}
}

You are using incorrect name of the checkbox element used for "cartId"

<input type="checkbox" name="checkbox" value="<%=cartID%>"/>

should be changed to

<input type="checkbox" name="cartID" value="<%=cartID%>"/>

Note: "name" of the checkbox

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