Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'"> [duplicate]
Asked Answered
L

1

18

I have an if statement that I am trying to perform with JSTL.

My code is below (the variables values is an ArrayList that contains a user defined object and type is a private property of that object, with public getter/setter methods):

<c:forEach items="${list}" var="values">
    <c:if test="${values.type}=='object'">
        <!-- code here -->
    </c:if>
</c:forEeach>

What would be the correct syntax of the part within the test attribute. The docs don't really help with that part http://download.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/index.html

Thanks.

Lenoralenore answered 16/1, 2011 at 17:7 Comment(0)
S
47

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

Schroer answered 16/1, 2011 at 17:11 Comment(4)
Thanks, I've tried it. It doesn't seem to resolve to false when I need it to. That's probably my mistake somewhere, if I figure it out and it's relevant, I'll post the solution here when I find it.Lenoralenore
The getType() must return a String to get it to work. Plus, it's case sensitive. That's why I used Object (with uppercase) in my 2nd example. Print ${values.type} plain to be sure.Schroer
I am looking over everything twice, thrice etc. and everything looks fine. The problem is not getting the value ... I have checked that, this part is working, the problem is that the condition is not resolving to false if the type=='number' ... I'll keep looking for clues.Lenoralenore
Thanks, all is solved :) was a long process, none of which is really relevant to the question, just common sense, so I won't explain.Lenoralenore

© 2022 - 2024 — McMap. All rights reserved.