Platinum Solutions Corporate Website


Inconsistent escaping in Spring MVC resource bundles

While our team was working on a Spring MVC application, we found that sometimes a message retrieved from a resource bundle had to have apostrophes escaped (by doubling them) and other times we didn't. I did some research to find out what was happening.

It turns out that Spring requires escaping or not depending upon how the resource is referenced.

You can see the issue with this example:

From the resource bundle:


phrase1.msg=This is the {0}th user''s message. It's very short.
phrase2.msg=This is some user''s message. It's very short.

From the html:


<spring:message code="phrase1.msg"/><br/>
<spring:message code="phrase1.msg" arguments="foo"/><br/>
<spring:message code="phrase2.msg"/><br/>
<spring:message code="phrase2.msg" arguments="foo"/><br/>

This results in:


This is the {0}th user''s message. It's very short.
This is the 5th user's message. Its very short.
This is some user''s message. It's very short.
This is some user's message. Its very short.

This same behavior occurs when validating fields in a form and calling Errors.rejectValue() with error arguments. Rejecting a value by calling


errors.rejectValue("field",new Object[],"defaultMessage");

is processed differently than


errors.rejectValue("field","defaultMessage");

The reason this happens is because if arguments are passed, Spring MVC uses java.text.MessageFormat to resolve the text. If there's no arguments passed, there's no need to use MessageFormat, and the escaping (described in the MessageFormat javadoc) isn't used.

In our application, we have some messages that get arguments passed into them, others which don't. So the resource bundle has to have a mix of double-quoted and single-quoted apostrophes. Something like this:


error.user.general.firstname=User's first name is required.
error.user.specific.firstname=User {0}''s first name is required.

Comments

Trace Windham (not verified) Wed, 1969-12-31 19:00

I am having the exact same issue described in this post.

I was wondering if you ever found a solution which enabled your resource strings to not have inconsistently escaped apostrophes.

If you have found a work around, I would love to hear about it.

Thanks,
Trace Windham
Nice Systems
Richardson, TX

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.

More information about formatting options