14
votes

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

5
<%= => gets printed to the output only if it appears outside of a JSP tag, as an answer below said. However, it does not get evaluated to a string but rather converted to whatever type the attribute expects. The <c:if> tag's test attribute is of type boolean so whatever expression the scriptlet returns will be coerced to a boolean. - mxxk
Though it's interesting to see that if you mix string and scriptlet within a JSP tag attribute, the engine gets confused and interprets the whole value as a string. That is, <c:if test="abc<%= true %>"> will not execute the scriptlet but instead coerce the string abc<%= true %> to a boolean via Boolean.valueOf() which returns false. stackoverflow.com/questions/8168821/… - mxxk

5 Answers

17
votes

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.

11
votes

You can also use something like

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

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.

2
votes

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

0
votes

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