25

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Alex Dowining
  • 980
  • 4
  • 19
  • 41

2 Answers2

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>
tk_
  • 16,415
  • 8
  • 80
  • 90
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 8
    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"%>` – Adriano Aug 13 '13 at 12:24
  • 1
    It would otherwise throw a rather self-explaining and quite googlable exception/error anyway. – BalusC Aug 13 '13 at 12:30
5

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.

anotherdave
  • 6,656
  • 4
  • 34
  • 65