Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

J2EE: Default values for custom tag attributes [duplicate]

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.

like image 922
Nick Avatar asked May 22 '10 01:05

Nick


2 Answers

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>
like image 136
Nick Avatar answered Oct 12 '22 22:10

Nick


With JSP EL and conditional operator it's a little bit cleaner and even shorter:

<c:set var="visible" value="${(empty visible) ? true : visible}" />
like image 22
G. Demecki Avatar answered Oct 12 '22 23:10

G. Demecki