Friday 11 September 2009

Accessing static constants in EL

Ever wanted to compare a value to a constant using Expression language in your UI ? Usually I would use the string representation hard-coded in the JSP which , if you have 1000 references in your UI code and you want to change the static constant value, you have a lot of work to do.

So you could

a) add accessors to your class for your contsants, which will work but is not very elegant when you have methods such as EG getAPPROVAL_STATUS_PENDING .

b) have a utility class which does the same as in a) and/or put all your constants in a map and import this class to the EL context.

I was not really happy with any of thse methods as they seemed clunky and unelegant. So I  did what all people do in this situation and used Google.

I came up with a Tag library from Jakarta called "unstandard"  which provided the functionality I needed. However it appears to be deprecated and only available as source code in one of their more obscure repository locations.
http://svn.apache.org/repos/asf/jakarta/taglibs/sandbox/unstandard/trunk

Since we have our own custom tag library on the project and I didnt really need all the functionality I took the description for the tag "useConstant" from the tld and integrated it with our Tag library descriptor  and tooks the classes
- org.apache.taglibs.unstandard.TagUtils
- org.apache.taglibs.unstandard.ClassUtils
- org.apache.taglibs.unstandard.UseConstantsTag

and put them in our tag code library.

Now I can access constants in UI expression language context in the following way. On the jsp page I wish to use the constants I add the declaration:

<mytaglibrary_prefix:useConstants classname="com.mypackagename.MyClass" var="MyClass" />



Then I can access my classes static constants using standard exrpession language syntax:
${MyClass.A_STATIC_FINAL_CONSTANT_VALUE}


I quite like this as its nice and clean, negates the need for string literals in the code corresponding to constant values , and will work seamlessly if constant values change.

A thank you to the Jakarta taglib team, my question is why is this not in the standard library and why do these utils appear deprecated?

No comments: