Expert Spring MVC and Web Flow

(Dana P.) #1

Message Sources


The Spring ApplicationContextimplements the org.springframework.context.MessageSource
interface used to resolve messages based on the locale of the user. When error codes are used
to reject property values or entire objects, Spring MVC asks the ApplicationContextfor a mes-
sage for a given locale.
The ApplicationContextchecks if a local bean named messageSourcehas been defined. If
no such bean is available, control is delegated to the parent ApplicationContext. If the parent
ApplicationContexts have no messageSource defined an exception is thrown.
To set up internationalization for validation error messages, configure org.springframework.
context.support.ResourceBundleMessageSourcewith bean name messageSource.
ResourceBundleMessageSourcetakes one or more base names to look up localized mes-
sages. These base names are appended with an underscore (“_”), the locale code (“NL”, “FR”,
“ES”, ...) and “.properties”, resulting in a filename that’s loaded from the classpath. These files
will be checked sequentially to resolve error codes, giving priority to the last message found.
ResourceBundleMessageSourceuses java.util.ResourceBundleinternally to load the mes-
sage files from the classpath. ResourceBundleinstances are cached to improve performance.
org.springframework.context.support.ReloadableResourceBundleMessageSourcereloads
message files dynamically when they have changed. Set the cacheSecondsproperty to define
the delay between refresh attempts (-1being the default to cache forever). This message
source uses Spring resource loaders to find message files defaulting to the default resource
loader of the ApplicationContext. When loading message files from the classpath it should be
noted that many application servers cache resources in the classpath. Changes made to mes-
sage files may thus not be refreshed; put your files in the /WEB-INFfolder to circumvent this.
Do not set cache seconds to 0 in production environments, as this will check the modification
timestamp of the message files on every message request.
Both ResourceBundleMessageSourceand ReloadableResourceBundleMessageSourceextend
the AbstractMessageSourcethat implements message handling. When error arguments are
passed, MessageFormatreplaces tokens in the message. A message example with tokens sup-
ported by MessageFormatis:

Your company name {0} is too long.

AbstractMessageSourcesupports MessageSourceResolvableinstances as error arguments
that will be resolved by AbstractMessageSource. See Listing 9-20.

Listing 9-20.Example of Message File Using Java Property Notation

cpyNameToLong=Your {0} {1} is too long.
cpyName=Company name

errors.rejectValue("name", "cpyNameTooLong", new Object[] { new
DefaultMessageSourceResolvable("cpyName"), company.getName() }, null)

278 CHAPTER 9 ■VALIDATION

Free download pdf