Question

I saw some code like the following in a JSP

<c:if test="<%=request.isUserInRole(RoleEnum.USER.getCode())%>">
    <li>user</li>
</c:if>

My confusion is over the "=" that appears in the value of the test attribute. My understanding was that anything included within <%= %> is printed to the output, but surely the value assigned to test must be a Boolean, so why does this work?

For bonus points, is there any way to change the attribute value above such that it does not use scriptlet code? Presumably, that means using EL instead.

Cheers, Don

Was it helpful?

Solution

All that the test attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"

<c:if test="true">Hello world!</c:if>

The code within the <%= %> returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if> tag looks for.

OTHER TIPS

You can also use something like

<c:if test="${ testObject.testPropert == "testValue" }">...</c:if>

The expression between the <%= %> is evaluated before the c:if tag is evaluated. So, supposing that |request.isUserInRole| returns |true|, your example would be evaluated to this first:

<c:if test="true">
    <li>user</li>
</c:if>

and then the c:if tag would be executed.

Attributes in JSP tag libraries in general can be either static or resolved at request time. If they are resolved at request time the JSP will resolve their value at runtime and pass the output on to the tag. This means you can put pretty much any JSP code into the attribute and the tag will behave accordingly to what output that produces.

If you look at the jstl taglib docs you can see which attributes are reuest time and which are not. http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html

<%=%> by itself will be sent to the output, in the context of the JSTL it will be evaluated to a string

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top