Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving cookie and array values in JSTL tags

Tags:

java

jsp

jstl

While retrieving cookies I need to use:

<c:forEach items="${cookie}" var="currentCookie">  
    ${currentCookie.value.name} </br>
</c:forEach>

But, while using custom arrays, why we need to skip the .value function?

<c:forEach items="${myList}" var="myList">  
    ${myList.name} </br>
</c:forEach>

Cookie contains a .getValue function() which returns the content of the cookie in string format, so how does using currentCookie.value.name work?

like image 717
Akash Avatar asked Jun 04 '12 14:06

Akash


1 Answers

The ${cookie} points to a Map<String, Cookie> with the cookie name as map key and the Cookie object as map value. Every iteration over a Map in <c:forEach> gives you a Map.Entry back which in turn has getKey() and getValue() methods. Your confusion is that the Cookie object has in turn also a getValue() method.

<c:forEach items="${cookie}" var="currentCookie">  
    Cookie name as map entry key: ${currentCookie.key}<br/>
    Cookie object as map entry value: ${currentCookie.value}<br/>
    Name property of Cookie object: ${currentCookie.value.name}<br/>
    Value property of Cookie object: ${currentCookie.value.value}<br/>
</c:forEach>

It's a Map<String, Cookie> because it allows you easy direct access to cookie value when you already know the name beforehand. The below example assumes it to be cookieName:

${cookie.cookieName.value}

Your list example is by the way invalid. The var should not refer the same name as the list itself.

like image 91
BalusC Avatar answered Oct 20 '22 13:10

BalusC