How to test if a string contains the given value in EL?

Alex Dowining picture Alex Dowining · Jul 3, 2012 · Viewed 62.7k times · Source

I have a list of String and i set it into a session:

 session.setAttribute("datas", result.getBody().getDatas());

Then i want to check in a JSP, if in the datas attribute doesn't contained the word "apple" for example. If this doesn't contained, then print a message doesn't contained. Initially i tried to do something like this:

   <c:forEach items="${datas}" var="data">
      <c:if test="${data!='apple'}">
          <p> Doesn't contained</p>
      </c:if>
   <c:for>          

But the aforementioned code, in case that the session contain the following values:

Apple Banana Lemon

Prints two times the message "Doesn't contained". I know that this is normal but how can i treat this in order to make what i want?

Answer

BalusC picture BalusC · Jul 3, 2012

The != tests for exact inequality. You need to use the fn:contains() or fn:containsIgnoreCase() function instead.

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

...

<c:forEach items="${datas}" var="data">
    <c:if test="${not fn:containsIgnoreCase(data, 'apple')}">
        <p>Doesn't contain 'apple'</p>
    </c:if>
</c:forEach>