Can I define default values in the TLD?

Is it possible to specify a default value for an attribute via the Tag Library Descriptor (TLD)?Some attributes are optional and I need a flexible way to define the value to use in case the page author doesn’t specify a value.
Answer:
You can’t set defaults via the TLD. If you can live with a hard coded default, just make the attribute optional and use a default value defined in the tag handler class if it’s not set by the page author.

If you need to be able to use different default values per application, I suggest you use a servlet context init parameter, defined in the web.xml file, and read it in the tag handler.

Example web.xml:

<web-app>
  ...
  <context-param>
    <param-name>
      com.mycompany.taglib.foo
    </param-name>
    <param-value>
      bar
    </param-value>
  </context-param>
  ...
</web-app>

Example tag handler class:

...
String optAttribute = getOptionalAttribute();
if (optAttribute == null) {
  ServletContext sc = pageContext.getServletContext();
  optAttribute = sc.getInitParameter("com.mycompany.taglib.foo");
}
...

I recommend that you use a parameter name that is guaranteed to be unique by following the naming convention used in this example (“com.mycompany.taglib.foo”) if you use this approach, so that you avoid possible name clashes with other tag libraries that may be used in the same application.

If you have many default values you need to define, you may consider using a special servlet (marked as “load-at-startup”) to initialize all defaults and use servlet init parameters instead of context init parameters. The servlet can then set context attributes for all default values, and the tag handlers can retrieve them exactly as above. One advantage with this approach is that the servlet can verify that all default values have been set to okay values when the application starts, so you don’t have to do that in all tag handlers. It also allows you to use short init param value names without risking name clashes with other parts of the application (you should still use the unique names for the context attributes though).

Another benefit of using a servlet to initialize the tag library like this is that it can also create other resources used by multiple tag handlers. In the book, I describe in detail an example of a servlet that makes a JDBC connection pool available to a set of tag handlers.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>