ArunDhwaj IIITH
ArunDhwaj IIITH

Reputation: 3903

How to compare two string in foreach loop of jsp/jstl?

I have the need to compare to strings in foreach loop.

My development environment:

1) MAC 10.11,

2) STS Version: 3.7.3.RELEASE

4) Spring Web MVC,

5) Pivotal tc Server Developer Edition v3.1

<c:set var="day" scope="session" value="${day}_${curId}"/>
<c:set var="new_day" scope="session" value="${2_456123}"/>


<c:if test="${day eq new_day}">
    <p> Both are same.      
</c:if>

But the system get hags at the line

<c:if test="${day eq new_day}">

Can somebody give any pointer ?

Thanks & Regards,

Arun Dhwaj

Upvotes: 0

Views: 2144

Answers (2)

rickz
rickz

Reputation: 4474

Here is demonstration code.

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<c:set var="day" scope="session" value="2"/>
<c:set var="curId" scope="session" value="456123"/>
<c:set var="day" scope="session" value="${day}_${curId}"/>
<c:set var="new_day" scope="session" value="2_456123"/>
<c:if test="${day eq new_day}">
     Both are same.      
</c:if>  

that prints: Both are the same.
If I change line number 5 to

<c:set var="new_day" scope="session" value="${2_456123}"/>  

which is what you posted, then I get an error message
contains invalid expression(s): javax.el.ELException: Failed to parse the expression [${2_456123}]

Upvotes: 1

Angelo Oparah
Angelo Oparah

Reputation: 673

Most likely the problem is caused by the following assignment

<c:set var="day" scope="session" value="${day}_${curId}"/>

With the above line you are assigning to the var day a value that comes from another variable with the same name but not necessarily with the same scope. In other words you might have already a variable called day that lives in another scope.

The default scope is the page scope, then you have in order the request, session and application therefore if a variable with the name day is retrieved in the page or request scope that variable will be considered when you perform the test and the variable you have defined in the session scope will be ignored.

You have two options

  1. Change the name of the variable defined in the session scope and use that name when performing the test

    <c:set var="niceday" scope="session" value="${day}_${curId}"/>
    
    <c:if test="${niceday eq ...}">
    
  2. Specify the scope of the variable used in the c:if tag

    <c:if test="${sessionScope.day eq ...}">
    

Hope that helped.

Upvotes: 1

Related Questions