Posts Tagged ‘controller’

Spring message translation found in JSP but not in controller

September 20, 2012 1 comment

Well, this one had me searching the web for a while, for no avail.  Finally figured it out!

Here’s the problem:

You defined everything correctly to setup your web app to be i18n compatible using Spring, you even got messages to be translated when in jsp view mode, but now you want to translate a message in your controller.  Sounds simple?  not so (unless you know the secret).

So you looked in the web, and found that you need to declare the following:

private MessageSource messageSource;

You already have the MessageSource bean setup (for the View part) in spring-servlet.xml like so:

<bean id=”messageSource”
    <property name=”basename” value=”/WEB-INF/i18n/messages” />
    <property name=”defaultEncoding” value=”UTF-8″/>
And  still, when you try to run it through messageSource in your controller, you get NOTHING, empty string.  And if you look closely, you will find that you have a DelegatingMessageSource in your messageSource property, with an empty parent source, which means it is EMPTY, i.e. always returns blank.

Well, here’s the thing:  Spring will setup a DelegatingMessageSource when it can’t find a message source definition.  What’s that, you say?  it DID find a message source, it found it for my View!  That’s true, it did find it for the view, but not for your controller.  Why is that?  I don’t really know, but fortunately, I know how to fix it 🙂

So, here’s the solution for this little challenge: move your messageSource definition from spring-servlet.xml to applicationContext.xml!

This will let Spring find your messageSource for your Controller as well, and all will be well.