J2EE: Default values for custom tag attributes

Nick picture Nick · May 22, 2010 · Viewed 12.2k times · Source

So according to Sun's J2EE documentation (http://docs.sun.com/app/docs/doc/819-3669/bnani?l=en&a=view), "If a tag attribute is not required, a tag handler should provide a default value."

My question is how do I define a default value as per the documentation's description. Here's the code:

<%@ attribute name="visible" required="false" type="java.lang.Boolean" %>
<c:if test="${visible}">
     My Tag Contents Here
</c:if>

Obviously, this tag won't compile because it's lacking the tag directive and the core library import. My point is that I want the "visible" property to default to TRUE. The "tag attribute is not required," so the "tag handler should provide a default value." I want to provide a default value, so what am I missing?

Any help is greatly appreciated.

Answer

Nick picture Nick · May 23, 2010

I'll answer my own question. I had an epiphany and realized that java.lang.Boolean is a class and not a primitive. This means that the value can be null, and after testing, this value most certainly is null.

When a value is not defined, then null is passed in. Otherwise, the value is whatever was passed in. So the first thing I do after declaring the attribute is to check if it's null. If it is null, then I know a value wasn't passed in or someone passed me null, and it should be converted to some default value:

<c:if test="${visible == null}"><c:set var="visible" value="${true}" /></c:if>