14

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.

Nick
  • 2,265
  • 7
  • 30
  • 34

2 Answers2

17

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>
halfer
  • 19,824
  • 17
  • 99
  • 186
Nick
  • 2,265
  • 7
  • 30
  • 34
  • See this: http://stackoverflow.com/questions/3136415/default-value-on-jsp-custom-tag-attribute – gavenkoa Apr 12 '13 at 06:58
  • 1
    In my case it does not work. My boolean attribute is never null: not setting it must be calling the constructor `new Boolean(null)` so I always get a non-null `false` value. – Rafa Mar 06 '14 at 09:49
5

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

<c:set var="visible" value="${(empty visible) ? true : visible}" />
halfer
  • 19,824
  • 17
  • 99
  • 186
G. Demecki
  • 10,145
  • 3
  • 58
  • 58