"Ошибка HTTP Status 500 - Для входной строки:" "", функция добавления к заказу работает только для верхней строки в таблице, а не для любой строки под ней - PullRequest
0 голосов
/ 28 февраля 2020

В настоящее время я работаю над проектом, и одним из аспектов является добавление продуктов в заказ. В настоящее время товары отображаются в виде таблицы, с кнопкой «добавить в заказ» рядом с каждой строкой. Проблема, с которой я сталкиваюсь, заключается в том, что кнопка «Добавить к заказу» будет работать только для верхнего ряда, и при попытке добавить к заказу произойдет ошибка для приведенных ниже рядов / продуктов. Любая помощь о том, почему это так, будет принята с благодарностью! Спасибо.

Сама ошибка: HTTP Status 500 - Для входной строки: "" (Вызывает ошибку, когда я нажимаю кнопку добавления заказа под первой строкой.)

Примечание: работа с JSP, java сервлетами и MySQL верстаком.

Код:

"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;
}
}
}

Редактировать:

Необходимо использовать ссылки на изображения, так как я не могу разместить их прямо здесь. Окончательный HTML для страницы продукта: Product homepage

Ошибка, которую я получаю: Error HTTP Status 500...

1 Ответ

0 голосов
/ 28 февраля 2020

ваша html структура неверна. Это первый шаг к вашей проблеме.

Ваш шаблон

<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>    

Правильный шаблон

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

upperCase и lowerCase

предупреждение о

 <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>                           

не является продуктом I d и p N ame? вместо productid и pname.

...