Tuesday 24 May 2011

Making Struts 2 and JSTL share message resources nicely.

It doesn't happen often, but occasionally ... you need to use your Struts 2 message resources in a jsp that is not part of a struts flow.

Normally, you have declared your struts 2 message resources (I put mine in global scope, i.e. global.properties at the root of my /WEB-INF/classes), and you use them as follows:

...

...


But in a simple JSP, you don't have access to these, so what do you do ? The obvious, simple solution is:

...

<%@ taglib prefix="fmt" 
           uri="http://java.sun.com/jsp/jstl/fmt" %>

...



...


Now, you might expect your text to appear right ? bzzzzt, Wrong! you get:

??some.random.text??

Now, why does this happen ? The answer is pretty simple, JSTL doesn't know about your struts message resources, you need to tell it about them.

This can be achieved with the following snippet in your web.xml:


  javax.servlet.jsp.jstl.fmt.localizationContextglobal
.


But be warned, as far as I can tell you can only specify one context, and thus you cannot use the struts 2 package style property cascading.

I personally use global propertiesm so this doesn't affect me.