Archive for the ‘web’ Category

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.