How do I do the equivalent of a java If-Else block using JSTL?

Dan picture Dan · Jun 2, 2011 · Viewed 62.4k times · Source

A quick JSTL question. I usually use scriptlets in my jsp pages, but have a conflict due to some other things in my page. I understand you can do something like this using JSTL, although I am not familiar with it. Here is what I would code using java for this:

if (var1.equalsIgnoreCase(var2)) { 

some html stuff

} else {

more html

}

So can this be converted and translated to be used with JSTL?

Thanks in advance and if you have any questions, just let me know.

Answer

BalusC picture BalusC · Jun 2, 2011

You can use <c:choose> for this. The equalsIgnoreCase() can be done by lowercasing the both sides by fn:toLowerCase().

<c:choose>
    <c:when test="${fn:toLowerCase(var1) == fn:toLowerCase(var2)}">
        Both are equal.
    </c:when>
    <c:otherwise>
        Both are not equal.
    </c:otherwise>
</c:choose>

Or when you're targeting a Servlet 3.0 container (Tomcat 7, Glassfish 3, JBoss AS 6, etc) with a web.xml declared conform Servlet 3.0, then you can invoke the equalsIgnoreCase() method.

<c:choose>
    <c:when test="${var1.equalsIgnoreCase(var2)}">
        Both are equal.
    </c:when>
    <c:otherwise>
        Both are not equal.
    </c:otherwise>
</c:choose>