JSTL and boolean values

I just realized something I did not know about the JSTL <c:if … > tag recently.

I had assumed that the item in the conditional test had to be either a Boolean object, or some other expression that would evaluate to a boolean primitive type. But JSTL is also smart enough to handle the String value “true” as a boolean as well (I didn’t know that before!)

As a Boolean object, this results in putting fish in the water:

In the Java:
request.setAttribute(“aquariumHasWater”, Boolean.valueOf(someMethodThatReturnsBooleanPrimitive()));

In the JSP:
<c:if test=”${aquariumHasWater}”> <aquarium:putFishInWater /> </c:if>

As a String, JSTL is smart enough to know the String value “true” and deal with it as a boolean

In the Java:
request.setAttribute(“aquariumHasWater”, Boolean.toString(someMethodThatReturnsBooleanPrimitive()));

In the JSP:
<c:if test=”${aquariumHasWater}”> <aquarium:putFishInWater /> </c:if>

Many times we have methods that return primitive boolean values.

Since primitives are not objects, we can’t put them in the Session/Request/etc. We have to convert it to some Object. A Boolean. Or A String. So I got to wondering, which way is better? Does it matter?

So I dug into the way it works (thanks to the JAD decompiler) and figured out that ultimately, the String value is “coerced” (org.apache.taglibs.standard.lang.jstl.Coercions) into being a Boolean object, by calling Boolean.valueOf() on the String. So, it would be slightly more efficient to just call Boolean.valueOf() on the primitive to begin with, rather than calling Boolean.toString() on the primitive, only for the taglib to turn around and just call valueOf() itself.

For anyone curious enough to see this coercion code, here’s a portion of the coerceToBoolean() method taken from the org.apache.taglibs.standard.lang.jstl.Coercions class:

public static Boolean coerceToBoolean(Object obj, Logger logger) throws ELException {
  String s;
  if(obj == null || "".equals(obj))
    return Boolean.FALSE;
  if(obj instanceof Boolean)
    return (Boolean)obj;
  if(!(obj instanceof String))
    break MISSING_BLOCK_LABEL_70;
  s = (String)obj;
  return Boolean.valueOf(s);

  ... // more

}
Advertisements
Posted in code. Tags: . Leave a Comment »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: