Help with foreach on jsp

Asked

Viewed 119 times

0

I’m trying to make an if in a jsp file, but I can’t print out all the values that are in the products table. For some reason my code only prints the first product and in the table I have 3 products.

            <c:forEach items="${products}"  var="product">
        <div class="w3-col l3 s4" style="width: 25rem;">
            <div class="w3-container">
            <img src="/w3images/" style="width:80%">
                ${product.productName}

            </div>
            <div class="w3-container">
                <h5 class="card-title">${product.productPrice}</h5>
                <p class="card-text">${product.productDescription}</p>
                <input id="productId" name="productId" type="hidden" value="${product.productId}">
                <button type="submit" class="w3-button w3-black" >Bid</button>

                <br>
            </div>
        </div>
</c:forEach>

My backend:

    private ProductService productService = new ProductService();

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


        String product_name = request.getParameter("userSearch");

        List<Product> productList = productService.searchProductName(product_name); //get product by name

        request.setAttribute("products", productList);

        request.getRequestDispatcher("/WEB-INF/views/userAds.jsp").forward(request, response);

        System.out.println(productList);


    }

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

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


        List<Product> productList = productService.searchProductName(userSearch); //get product by name

        request.setAttribute("products", productList);

        request.getRequestDispatcher("/WEB-INF/views/userAds.jsp").forward(request, response);

    }   

}

1 answer

0


Your foreach seems to be ok, is the problem not in the backend? Maybe your products object is not being filled with the three items.

Debug your Java code to check this, or dump the JSP object like this:

<!--
  ${products}
-->

I believe this will show the content of the object (calling toString) as comment in the generated html, so you can check by clicking on 'View Source' in the browser.

In any case, it would be interesting to put the backend code to help in the analysis.

  • I added my backend to the question. If I put products, it gives error and the page does not open.

  • Cool, you even put a debug in the line that calls productService.searchProductName() to see if you are returning all products? Another thing I noticed in your code is that you are using a request parameter calling 'userSearch' to be used as 'product name', this is correct?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.