ParUpadh
ParUpadh

Reputation: 57

Access individual elements of List(POJOs) in jsp using <jsp:Usebean>

I have a servlet which uses Hibernate and retrieves "Products" table from my DB.

 Session session = HibernateUtil.getSessionFactory().openSession(); 
    Transaction tx = null; 

   tx= session.beginTransaction();
   Query query=session.createQuery("from Products");
    List mylist1=query.list();
    tx.commit();
    session.close();
    HttpSession httpSession=request.getSession();
    httpSession.setAttribute("Products", mylist1);

    RequestDispatcher dispacther=request.getRequestDispatcher("index.jsp");
    dispacther.forward(request, response);

I have forwarded the List of Products(pojo) to my jsp. My question is how to retrieve individual elements of List and access them using <jsp:useBean> in my jsp.

Upvotes: 0

Views: 1132

Answers (1)

BalusC
BalusC

Reputation: 1108802

You don't need the <jsp:useBean> thing at all. You're already using a servlet to manage the model. The model is already directly available in JSP via EL expression ${Products} (although you'd better rename the thing to products, exactly following standard Java variable naming conventions).

httpSession.setAttribute("products", mylist1);

You can obtain the invididual elements by explicitly specifying their index using the brace notation:

${products[0]}
${products[1]}
${products[2]}
...

Or, better, just loop over them using JSTL's <c:forEach>:

<c:forEach items="${products}" var="product">
    ${product}
</c:forEach>

Your next question shall probably be "How do I print the properties of each individual product in tabular format?". Well, just put the <c:forEach> in a HTML <table><tr><td> and reference the properties in ${bean.propertyname} format. Assuming that your Product has id, name, description and price properties, here's how it could look like:

<table>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Description</th>
        <th>Price</th>
    </tr>
    <c:forEach items="${products}" var="product">
        <tr>
            <td>${product.id}</td>
            <td><c:out value="${product.name}" /></td>
            <td><c:out value="${product.description}" /></td>
            <td><fmt:formatNumber value="${product.price}" type="currency" /></td>
        </tr>
    </c:forEach>
</table>

See also:

Upvotes: 1

Related Questions