Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jsp

jstl

el

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?

like image 431
Alex Dowining Avatar asked Jul 03 '12 17:07

Alex Dowining


2 Answers

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>
like image 79
BalusC Avatar answered Dec 09 '22 20:12

BalusC


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.

like image 35
anotherdave Avatar answered Dec 09 '22 19:12

anotherdave