Reputation: 1670
I am using JSTL to iterate Spring's model values in my JSP.
I display the two dates in my JSP using JSTL.
Below is my Java code:
model.put("oldest",timesheetService.getOldestPendingTimesheet(userDetails));
model.put("pending", timesheetService.getNextOldestPendingTimesheet(userDetails));
JSP Code:
<c:choose>
<c:when test="${not empty model.oldest}">
<c:out value="${model.oldest}"/>
</c:when>
<c:when test="${not empty model.pending}">
<c:out value="${model.pending}"/>
</c:when>
</c:choose>
I display the both dates in outside of the <c:choose>
tag. It's printing like below:
oldest:Tue Nov 04 00:00:00 IST 2014
Pending:Sun Nov 09 00:00:00 IST 2014
Oldest Date
is printing inside the <c:when>
tag, but bpending
is printing only outside of the <c:choose>
tag and not printing inside the <c:when>
tag.
What's wrong with the above code?
Upvotes: 0
Views: 446
Reputation: 1
The <c:choose>
works like a Java switch
statement. It lets you choose between a number of alternatives. Where the switch
statement has case
statements, the <c:choose>
tag has <c:when>
tags. So, if the one of <c:when>
satisfies a condition then others <c:when>
will not execute, like if you put a break
condition after case
block. You should use <c:choose>
if you want to print either of properties. If you want to print them both then you'd better use <c:if>
to test for emptiness. If you want still to use <c:choose>
then you need it to do in a separate tags. Also for formatting a date use <fmt:formatDate>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:choose>
<c:when test="${not empty model.oldest}">
<fmt:formatDate type="both"
dateStyle="long" timeStyle="long"
value="${model.oldest}" />
</c:when>
</c:choose>
<c:choose>
<c:when test="${not empty model.pending}">
<fmt:formatDate type="both"
dateStyle="long" timeStyle="long"
value="${model.pending}" />
</c:when>
</c:choose>
Upvotes: 1
Reputation: 2472
Another option can be -
<c:choose>
<c:when test="${not empty model.oldest}">
<c:out value="${model.oldest}"/>
</c:when>
<c:otherwise>
<c:when test="${not empty model.pending}">
<c:out value="${model.pending}"/>
</c:when>
</c:otherwise>
</c:choose>
Upvotes: 0
Reputation: 24433
That's because when you have several <c:when>
in <c:choose>
, the first one is interpreted as if
and all the others as else if
. So, your first condition is satisfied and the second when
is ignored.
If you want to print both of them depending on non-exclusive conditions, better use <c:if>
. It is also easier to read than <c:choose>
construct, when you have few conditions.
<c:if test="${not empty model.oldest}">
<c:out value="${model.oldest}"/>
</c:if>
<c:if test="${not empty model.pending}">
<c:out value="${model.pending}"/>
</c:if>
Upvotes: 2