tags:

views:

18453

answers:

5

Hi,

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

+1  A: 

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

Sindri Traustason
A: 

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

Javaxpert
+3  A: 

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.

Mike Spross
+5  A: 

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.

Michael Angstadt
Strictly speaking, doesn't the code within <%= %> returns a String, rather than a boolean?
Don
@Don, request.isUserInRole() (which is the one within <%= and %>) does return a boolean value. Hope this is what you were asking.
Shivasubramanian A
+1  A: 

You can also use something like

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