Home > Software engineering >  use <c:forEach> to loop through element
use <c:forEach> to loop through element

Time:08-19

i tried looping through an item based on the values available on the database but my index page came out blank. please what could have cuz this.. i have values already inserted in the mysql database. but it can't appear on the index page

my index page code:

<c:forEach var="p" items="${products}">
    <jsp:useBean id="p" />
    <div >
        <div >
            <div >
                <div >
                    <img  src="" alt=" ">
                </div>
            </div>
            <div >
                <div >
                    <h6>${p.price}</h6>
                    <h4>${p.productName}</h4>
                    <p>Ras effic itur metusga via suscipit</p>
                    <button type="button"  data-toggle="modal"
                            data-backdrop="static" data-keyboard="false" data-target="#easy" >buy</button>
                </div>
            </div>
        </div>
    </div>
</c:forEach>

this is my servlet code

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    response.setContentType("text/html;charset=UTF-8");
    try
    {

        List<Products> products = ProductDAO.getAllProducts();

        request.setAttribute("products", products);
    }
    catch(Exception xcp)
    {

    }
}

CodePudding user response:

I guess that you're missing the import of the JSTL library.

Thus the <c:forEach> actually does nothing, it doesn't loop around the list, and doesn't put any value in p.

Adding the import should fix the issue:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<c:forEach var="p" items="${products}" >
    ${p.productName} - ${p.price}
</c:forEach>

Note that the <jsp:useBean ...> line is useless and should be removed.

  • Related