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

2

24

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?

Hale answered 3/7, 2012 at 17:17 Comment(0)
J
55

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>
Jeweljeweler answered 3/7, 2012 at 17:20 Comment(2)
Don't forget to declare the relevant taglib at the top of your jsp <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>Semanteme
It would otherwise throw a rather self-explaining and quite googlable exception/error anyway.Jeweljeweler
J
4

You'd need to us fn:toLowerCase():

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

Using fn:containsIgnoreCase() will check for a partial match (the presence of a substring within a given string). So if you're data was ["Pineapple", "Banana", "Lemon"] for example you would also get a match. I'm presuming you'd only want to match against 'apple' as a complete string.

Jeminah answered 3/7, 2012 at 22:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.