Question

I've got a List of Products obtained from a database query.

In each Product there is a Date_in and a Date_out variable of Calendar type.

What I want to do is pass these Products to a jsp view, so that I can build a table with all their informations. To do so I need to convert the Calendar dates to a more suitable format (like a String), and I've got an utility for this.

My problem is: How can I pass each converted date_in/date_out to the request.setAttribute, for each Product in the List?

Here's what I've got.

in ProductAction:

List<Product> products = service.viewActiveProducts();
    for(Product product: products) {
        String date_inToString = DateConversionUtility.calendarDateToString(product.getDate_in());
        String date_outToString = DateConversionUtility.calendarDateToString(product.getDate_out());
    }

    request.setAttribute("products", products);

in the jsp:

<table>
  <tr class="index">
    <td>Id</td>
    <td>Date IN</td>
    <td>Date OUT</td>
  </tr>
<c:forEach items="${requestScope.products}" var="product">
  <tr>
    <td>${product.oid}</td>
    <td>${product.date_in}</td>
    <td>${product.date_out}</td>
  </tr>
</c:forEach>
</table>

(Right now product.date_in and product.date_out are in a Calendar format. I want them in a String format).

Was it helpful?

Solution

You can create a custom JSTL function and use it directly in your JSP EL tags.

<td>${product.oid}</td>
<td>${nspace:formatDate(product.date_in)}</td>
<td>${nspace:formatDate(product.date_out)}</td>

Where nspace is the xml namespace assigned to your library and formatDate your method. A couple of links:

http://www.noppanit.com/how-to-create-a-custom-function-for-jstl/ http://anshulsood2006.blogspot.com.es/2012/03/creating-custom-functions-in-jsp-using.html

OTHER TIPS

You can pass entire list to jsp by request.setAttribute(String,Object);

List<Product> products = service.viewActiveProducts();
request.setAttribute("products", products);

Your Product class should be implementing Serializable interface

To get your properties date_in and date_out in string format, convert them into string and have two more properties in Product class with names say dateInString and dateOutString and set their values like

for(Product product: products) {
product.setDateInString(DateConversionUtility.calendarDateToString(product.getDate_in()));
product.setDateOutString(DateConversionUtility.calendarDateToString(product.getDate_out()));
}

In jsp, you can user JSTL to get the properties or field of Products object iterating list

<c:forEach items="${products}" var="product"> 
  <tr>
    <td>${product.oid}</td>
    <td>${product.dateInString}</td>
    <td>${product.dateOutString }</td>
  </tr>
</c:forEach>

Make a getDate_inString() and getDate_outString methods in Product bean that will print what you want. Then, in the jsp you can use ${product.date_inString}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top