问题
In a servlet I have:
HashMap eventsByDayNo = new HashMap();
eventsByDayNo.put (new Integer(12), "day 12 info");
eventsByDayNo.put (new Integer(11), "day 11 info");
eventsByDayNo.put (new Integer(15), "day 15 info");
eventsByDayNo.put (new Integer(16), "day 16 info");
request.setAttribute("eventsByDayNo", eventsByDayNo);
request.setAttribute("daysInMonth", new Integer(31));
And in a jsp I have:
<c:forEach var="dn" begin="1" end="${daysInMonth}" step="1" varStatus="status">
Day Number=<c:out value="${dn}" /> Value=<c:out value="${eventsByDayNo[dn]}" /><br>
</c:forEach>
The above JSTL works fine, but if I try to offset the day number <c:out value="${eventsByDayNo[dn+3]}" />
none of the hashmap entries are not printed. Any answers as to why not?
The above is just a proof of concept for my real application.
回答1:
My guess is that dn+3
has type java.lang.Double
, not java.lang.Integer
(which you may expect).
<ul>
<c:forEach var="dn" begin="1" end="${daysInMonth}" step="1">
<li>
<c:set var="dnplus3" value="${dn+3}" />
dn=<c:out value="${dn}" />
dnplus3=<c:out value="${dnplus3}" />
class=<c:out value="${dnplus3.class.name}" />
</li>
</c:forEach>
</ul>
回答2:
Numbers (at least, whole numbers) in EL are implicitly treated as Long
. So replace your Map<Integer, String>
by a Map<Long, String>
and it will work.
来源:https://stackoverflow.com/questions/3919025/jstl-and-hashmap-not-working