views:

72

answers:

1

Is it possible to write a custom JSP tag to take an i18n message key and output the translation phrase for the given request?

Normally in JSP/JSTL, I do:

<fmt:message key="${messageKey}"><fmt:param>arg1</fmt:param></fmt:message>

And I get the translation phrase. Now I need to do the following (there's a good reason for this):

<custom:translate key="${messageKey}" arg="arg1"/>

But I don't know how to look up the translation in the custom tag code. The TagSupport base class provides a pageContext from which I can get a ServletRequest which has the Locale... but how do I then look up the translation for a key?

I use Spring 3.0 and in my application-context.xml, I've defined a ReloadableBundleMessageSource so I can call:

messageSource.getMessage(
    key, new Object[] {arg}, pageContext.getRequest().getLocale()
);

but I don't think I can inject messageSource into a custom tag, can I? Otherwise I can instantiate a new one, but would it load my tens of thousands of translations for every call? I don't want to resort to making messageSource a static member of a static class.

+1  A: 

I don't do Spring, but in "plain" JSP you can just put the ResourceBundle instance in the session scope with help of a Filter or Servlet

ResourceBundle bundle = ResourceBundle.getBundle(basename, request.getLocale());
request.getSession().setAttribute("bundle", bundle);

And treat it in JSP like any other bean in EL.

${bundle[messageKey]}

It must be possible to have Spring to put that as a bean in the session scope.

BalusC
hmmm.. how do I get a message from a ResourceBundle that has parameters? Rather than attaching to each session, it's probably easier to attach this to each page as a model attribute.
at
Oh sorry, I overlooked that part. You can do that using [`MessageFormat#format()`](http://download-llnw.oracle.com/javase/6/docs/api/java/text/MessageFormat.html#format%28java.lang.String,%20java.lang.Object...%29). And yes, you can of course also just put it in the request scope. Creating new one on every HTTP request is only a bit more expensive after all.
BalusC
Ok I got it, thanks.
at