0

I am currently working on a project, and one aspect is adding products to an order. Currently, the products are displayed in a table, with a button "add to order" next to each row. The issue I am encountering is that the "Add to order" button will only work for the top row, and will cause an error for the below row(s)/products when I try to add to order. Any help on why this is the case would be greatly appreciated! Thank you.

The error itself: HTTP Status 500 - For input string: "" (Invokes error when I click the add order button below the first row.)

Note: working with JSP's, java servlets and MySQL workbench.

Code:

"CustomerProductsNew.jsp":

<%    Statement stat = null;
    ResultSet rs = null;
    stat = conn.createStatement(); 
    String search = request.getParameter("productSearch");
    String qry; //sets data variable to hold the SQL query

    String q = request.getParameter("cmbCategory");

    if (search != null) {
        qry = "SELECT productid, pname, category, priceperunit, qtyavailable, pdesc FROM product WHERE pname LIKE '%" + search + "%' OR category LIKE '%" + search + "%' OR priceperunit LIKE '%" + search + "%' OR pdesc LIKE '%" + search + "%'";
    } else {
        qry = "SELECT productid, pname, category, priceperunit, qtyavailable, pdesc FROM product";
    }

    rs = stat.executeQuery(qry); //executes SQL query


%>
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Description</th>
                        <th>Stock Available</th>
                        <th>Unit Price</th>
                        <th>Quantity Required</th>
                        <th>Add To Order</th>
                    </tr>
                </thead>
                <tbody>


                    <% while (rs.next()) {%>

                    <tr>    
                        <td width="5%"><input type="text" name="productID" value="<%=rs.getInt("productid")%>" class="border-0" size="1" readonly></td>
                        <td width="5%"><input type="text" name="productName" value="<%=rs.getString("pname")%>" class="border-0" size="20" readonly></td>
                        <td width="8%"><%=rs.getString("category")%></td>
                        <td width="25%"><%=rs.getString("pdesc")%></td>

                        <td width="5%"><%=rs.getDouble("qtyavailable")%></td>
                        <td width="5%"><input type="number" name="pricePerUnit" value="<%=rs.getDouble("pricePerUnit")%>" class="border-0" size="1" readonly></td>

                        <td width="5%"><input id="randomno" type="number" name="quantity" size="1"></td>

                        <td width="5%"><a href="" onclick="this.href='${pageContext.request.contextPath}/orderservlet1?productID=<%=rs.getInt("productid")%>&productName=<%=rs.getString("pname")%>&pricePerUnit=<%=rs.getDouble("pricePerUnit")%>&quantity='+document.getElementById('randomno').value">Add to Order</a></td>                           

                    </tr>

                    <% }%>

                </tbody>
            </table>

"OrderServlet1.java":

@WebServlet("/orderservlet1")
public class OrderServlet1 extends HttpServlet {

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

         HttpSession session = request.getSession();

        int productID = Integer.parseInt(request.getParameter("productID"));
        String productName = request.getParameter("productName");
        double pricePerUnit = Double.parseDouble(request.getParameter("pricePerUnit"));
        int quantity = Integer.parseInt(request.getParameter("quantity"));

        OrderDAO orderBean = null;

        Object objOrderBean = session.getAttribute("order");

        if (objOrderBean != null) {
            orderBean = (OrderDAO) objOrderBean;
        } else {
            orderBean = new OrderDAO();
            session.setAttribute("order", orderBean);
        }

        orderBean.addOrderItem(productID, productName, pricePerUnit, quantity);
        response.sendRedirect("CustomerProductsNew.jsp");

    }
}

"OrderDAO.java":

public class OrderDAO {
     private ArrayList allOrderItems = new ArrayList();
    private double orderTotal;

    public int getOrderItemCount() {
        return allOrderItems.size();
    }
 public void addOrderItem(int prodID, String prodName, double pricePerU, int qty) {
        double dblTotalCost = 0.0;
        double pricePerUnit = 0.0;
        int iQty = 0;
        OrderItem orderItem = new OrderItem();
        try {
            pricePerUnit = pricePerU;
            iQty = qty;
            if (iQty > 0) {
                dblTotalCost = pricePerUnit * iQty;
                orderItem.setProductID(prodID);
                orderItem.setProductName(prodName);

                orderItem.setPricePerUnit(pricePerU);
                orderItem.setQuantity(iQty);
                orderItem.setTotalCost(dblTotalCost);
                allOrderItems.add(orderItem);
                calculateOrderTotal();
            }
        } catch (NumberFormatException nfe) {
            System.out.println("Error while parsing from String to primitive types: " + nfe.getMessage());
            nfe.printStackTrace();
        }
    }

    public void addOrderItem(OrderItem orderItem) {
    allOrderItems.add(orderItem);
 }

 public OrderItem getOrderItem(int iItemIndex) {
  OrderItem orderItem = null;
  if(allOrderItems.size()>iItemIndex) {
   orderItem = (OrderItem) allOrderItems.get(iItemIndex);
  }
  return orderItem;
 }

 public ArrayList getOrderItems() {
  return allOrderItems;
 }
 public void setOrderItems(ArrayList allOrderItems) {
  this.allOrderItems = allOrderItems;
 }
 public double getOrderTotal() {
  return orderTotal;
 }
 public void setOrderTotal(double dblOrderTotal) {
  this.orderTotal = dblOrderTotal;
 }

 protected void calculateOrderTotal() {
  double dblTotal = 0;
  for(int counter=0;counter<allOrderItems.size();counter++) {
   OrderItem orderItem = (OrderItem) allOrderItems.get(counter);
   dblTotal+=orderItem.getTotalCost();

  }
  setOrderTotal(dblTotal);
 }

}

"OrderItem.java":

public class OrderItem {
private int productID;
private String productName;
private String category;
private String pdesc;
private double pricePerUnit;
private int quantity;
private double totalCost;

public int getProductID() {
    return productID;
}

public void setProductID(int productID) {
    this.productID = productID;
}

public String getProductName() {
    return productName;
}

public void setProductName(String productName) {
    this.productName = productName;
}

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}

public String getPdesc() {
    return pdesc;
}

public void setPdesc(String pdesc) {
    this.pdesc = pdesc;
}

public double getPricePerUnit() {
    return pricePerUnit;
}

public void setPricePerUnit(double pricePerUnit) {
    this.pricePerUnit = pricePerUnit;
}

public int getQuantity() {
    return quantity;
}

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

public double getTotalCost() {
    return totalCost;
}

public void setTotalCost(double totalCost) {
    this.totalCost = totalCost;
}
}
}

Edit:

Have to use links to images as I can't place them directly here yet. Final HTML for Product page: Product homepage

Error I'm getting: Error HTTP Status 500...

Reporter
  • 3,897
  • 5
  • 33
  • 47
Macca99
  • 11
  • 2
  • Like [Java - escape string to prevent SQL injection](https://stackoverflow.com/questions/1812891/java-escape-string-to-prevent-sql-injection). Add `%` to search string and then treat that as the param to the prepared statement. – danblack Feb 27 '20 at 21:34
  • show us the final html in browser. (the 4 or 5 first in table) – Eric Feb 28 '20 at 00:26
  • Added images there of the final HTML. @Eric – Macca99 Feb 28 '20 at 09:15
  • Thank you @danblack I'll add that to my search code! – Macca99 Feb 28 '20 at 09:17
  • You cannot use same `id` to multiple html elements, in your jsp code your quantity have `id="randomno"` this will work for first row and afterwards it will return `null` thats the reason of error you are getting in servlet. – Swati Feb 28 '20 at 14:30
  • @Swati - that stopped the error, however it still not adding to the order. What do you suggest I do? – Macca99 Feb 28 '20 at 15:09
  • alternative here may be to assign dynamic `id` to your quantity input and passing the same to your servlet. – Swati Feb 28 '20 at 15:20
  • @Swati I will try that. Thank you very much for your suggestion and help! – Macca99 Feb 29 '20 at 10:36

2 Answers2

0

change input type number to text in "CustomerProductsNew.jsp"

" class="border-0" size="1" readonly>
                    <td width="5%"><input id="randomno" type="number" name="quantity" size="1"></td>

above input type is wrong because you trying to store integer in string

" class="border-0" size="1" readonly>
                    <td width="5%"><input id="randomno" type="text" name="quantity" size="1"></td>
-1

your html structure is wrong. It's first step for your issue.

Your template

<table>
  <tbody>
    <tr>
    <th>ID</td>
    <th>Name</td>
    <tr>

    <% while (rs.next()) {%>
      <tr>    
        <td>some things</td>
        <td>some things</td>
      </tr>
    <% }%>
  </tbody>
</table>    

Correct Template

 <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
      </tr>
    </thead> 
    <tbody>
      <% while (rs.next()) {%>
       <tr>    
         <td>some things</td>
       </tr>
    </tbody>
</table>

upperCase and lowerCase

warn on

 <td width="5%"><a href="" onclick="this.href='${pageContext.request.contextPath}/orderservlet1?productID=<%=rs.getInt("productid")%>&productName=<%=rs.getString("pname")%>&pricePerUnit=<%=rs.getDouble("pricePerUnit")%>&quantity='+document.getElementById('randomno').value">Add to Order</a></td>                           

is not productId and pName ? instead productid and pname.

Eric
  • 608
  • 4
  • 11
  • Thank you @Eric, I have changed my code to replicate your answer above. Still encountering the same error. Could it be that I'm using a table format? Might it work without the table? – Macca99 Feb 28 '20 at 09:19
  • I wanted to say: show the source code of the html code produced for a few lines, especially the onclick = xxxx part – Eric Feb 28 '20 at 18:34