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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With