Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSTL c:set condition

Tags:

java

jsp

jstl

Need your help figuring this thing out.
Scenario: On my JSP, I am trying to print

<b>Season 1: ${season}</b>

<b>Season 2: ${season}</b>

this prints fine the first time (Both seasons print as "winter" initially). Now I wanted to add an if condition to change season value like:

<c:if test="${temperature eq 'HOT' || 'VERYHOT'}">
       <c:set var="season" value="summer is here" />
 </c:if>

On executing this if condition, Season 1 changes to "summer is here" but Season 2 stays the same. Why it stays so? Season 1 is part of page1.jsp and Season 2 is part of page2.jsp and they are included inside parentPage.jsp

like image 387
t0mcat Avatar asked Sep 16 '11 18:09

t0mcat


1 Answers

Two problems:

First, your comparison is not valid. The 2nd condition is always true. Fix it accordingly:

<c:if test="${temperature eq 'HOT' || temperature eq 'VERYHOT'}">

Second, you're storing the variable in the default page scope which is not shared among included JSP pages. Store it in request scope instead.

<c:set var="season" value="summer is here" scope="request" />

Update: as turns out per the comments, those JSPs do not participate in the same request. You should then grab the session scope (and be aware that this way the variable get exposed in all requests in all browser windows/tabs! this is not per-se desireable). You should only ensure that you're specifying the scope in every <c:set var="season">.

<c:set var="season" value="some value" scope="session" />

The EL expression ${season} will namely search for the first non-null attribtue in respectively the page, request, session and application scopes. So if you do a <c:set> without an explicit scope, then it will be stored in page scope and obtained in same page as such.

like image 153
BalusC Avatar answered Oct 11 '22 23:10

BalusC