Search code examples
jsfjavabeansnetbeans-8

Java Bean & JSF formatting List of Dates


I'm fairly new to JSF, Java Beans, and JPQL. I have 2 nested c:forEach tags. The first loops for each DISTINCT Date, the second for each each 'timeslot' on that date.

<c:forEach var="d" items="#{bean.listedDates(1)}" >
     #{d.date}   <!-- this displays '11' -->
    <ui:decorate template="template for day" />
    <c:forEach var="item" items="#{bean.listedTimeslots(1, d.date)}">
        <ui:decorate template="template for time-slot row" />       
    </c:forEach>                                    
</c:forEach>

bean.java - listedDates

public List<Date> listedDates(int idPass) {        
    List<Date> dateQueue = em.createQuery("SELECT DISTINCT l.date FROM table1 l WHERE l.id = :id")
    .setParameter("id", idPass)
    .getResultList();

    System.out.println("DATES DISPLAYED BELOW");
    System.out.print(dateQueue);
    return dateQueue;
}

Console

Info: DATES DISPLAYED BELOW

Info: [Wed Feb 11 00:00:00 GMT 2015, Wed Mar 11 00:00:00 GMT 2015, Sat Apr 11 00:00:00 BST 2015]

However, #{d.date} displays '11'. And this error occurs in regards to passing d.date into listedTimeslots.

Cannot convert 11 of type class java.lang.Integer to class java.util.Date

I need to format my list of dates from [Wed Feb 11 00:00:00 GMT 2015] to [YYYY-MM-DD] (Which is also how its displayed in the database), can anyone give me any pointers? Thanks!


Solution

  • The problem is how you address your bean property.

    When you use #{d.date} you are telling your bean to access a property of the java.util.Dateinstead of the whole date value you are expecting.

    The property you are accessing here is date through getDate() which returns the number of the day of the month which has int as a type according to the Java 6 documentation of java.util.Date which I think you are using to compile and run this code.

    To solve this problem you will need to change the following EL :

    Use #{d} instead of #{d.date}

    Your code should look something like this :

    <c:forEach var="d" items="#{bean.listedDates(1)}" >
      #{d}   <!-- changed-->
      <ui:decorate template="template for day" />
      <c:forEach var="item" items="#{bean.listedTimeslots(1, d)}">  <!-- changed-->
         <ui:decorate template="template for time-slot row" />       
       </c:forEach>                                    
    </c:forEach>
    

    References:

    http://docs.oracle.com/javase/6/docs/api/java/util/Date.html