spring:message tag and resouce bundle

October 3, 2010 § Leave a comment

Problem
Using spring mvc framework, I came across a weird situation with handling the resource bundle messages… here is what I faced…

<spring:message code="messageCode" arguments="First Name"/>

If the value in resource bundle looked like

messageCode=You've not selected the required field {0}.

… the actual value rendered on the page would look like

messageCode=Youve not selected the required field First Name.

… note the apostrophe missing!

However if the spring tag looked like

<spring:message code="messageCode" />

… result looks like

messageCode=You've not selected the required field {0}.

… not the apostrophe there!

Solution
It means the apostrophe is filtered out only when there is a parameter replacement requested using the attribute “arguments” on the spring tag. It will be the first thought in anybody’s mind to replace all single apostrophe with a double apostrophe in the resource bundle so that double apostrophes get filtered out to single and correct sentence is rendered. However, with the later case above, it would render double apostrophes. Typically we need a mix of tags with and without arguments.

Solution involves three steps:

  1. Keep all messages in the resource with double apostrophes
  2. messageCode1=You''ve not selected the required field {0}. This is a message with parameter
    messageCode=You''ve not filled in all the details. This is a message without parameter
    
  3. All Spring message tags where we know are going to have arguments, code them usual
  4. <spring:message code="messageCode1" arguments="First Name"/>
    
  5. All Spring message tags not requiring any argument, code them to pass on an EMPTY SPACE argument
  6. <spring:message code="messageCode2" arguments=" "/>
    

    Empty space triggers the replacement algorithm (spring uses Java MessageFormat to do this). It replaces double apostrophes with a single apostrophe

Both messages get rendered correctly:

You've not selected the required field First Name. This is a message with parameter

You've not filled in all the details. This is a message without parameter

Done!

Leave a comment

What’s this?

You are currently reading spring:message tag and resouce bundle at Sunil writes....

meta