Archive for January, 2008

Tame Web URLs with JSTL and Enums

Monday, January 7th, 2008

I discovered Java Enums last year. My favorite usage thus far is using them in conjunction with JSTL to construct web URLs:

<c:url value='/myapp/JustDoIt.htm' var='myHref'>
<c:param name='<%=WebParam.foo.name()%>' value='1' />
<c:param name='<%=WebParam.bar.name()%>' value='2' />
</c:url>
<a href="${myHref}>Just Do It</a>

…which results in the following HTML:

<a href="/myapp/JustDoIt.htm?foo=1&bar=2">Just Do It</a>

To retrieve the parameter values from within the controller, simply use the enum:

String foo = request.getParameter(WebParam.foo.name());
String bar = request.getParameter(WebParam.bar.name());

The best part is compliance with the DRY principle. The parameter names are uniform and not duplicated through out the web application making it easy to both search for usage and rename parameters.

Got a NoSuchMethodError? Check Your Classpath for Duplicate Classes and/or Interfaces.

Friday, January 4th, 2008

Java documentation explains NoSuchMethodError like so:

Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.

So, you’ll appreciate how surprised I was to receive such an error when I modified the signature on a service method and clearly was using the new method appropriately in my webapp. Service module compiled cleanly? Check. Service module installed in the Maven repo? Check. Webapp picking up newly installed service module from Maven repo? Check. WTF!?

And then, Eureka! I had split a bigger module containing transactional and data access objects into respective “service” and “DAO” modules in the past. Like any divorce, it got messy when the “assets” were divided between the two. An interface was moved to “service” but also remained behind in “DAO”. The webapp was compiled against a newer “service” interface, but at runtime the legacy “DAO” was resolved by the webapp via the classpath resulting in a mid-air collision. BAM!