How to I define and get locale-based messages in Spring MVC?

15,455

It depends on what you want to do with this text. The first possibility is to get the message programmatically:

@Autowired
private MessageSource messageSource;

@RenderMapping(params = "render=details")
public String showDetails (Model model, Locale locale) {
    messageSource.getMessage(<your key goes here>, null, locale);
}

This way is very uncommon, cause you have to get the message keys form the Errors object by yourself.

Another more common way is to use the build in view extensions shipped with spring mvc. You didn't wrote it but I guess your using JSPs. In that case you can simply write something like this in your JSP:

<!-- showing errors -->
<div>
    <form:errors path="*" />
</div>

<!-- showing arbitrary messages -->
<div>
    <spring:message code="${success.messageKey}"/>
</div>

For further reading I suggest you http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/view.html

Share:
15,455
David Parks
Author by

David Parks

Merge Keep

Updated on June 04, 2022

Comments

  • David Parks
    David Parks almost 2 years

    I want to define a set of error messages so that when validation errors generate codes, those codes pick up the corresponding error message and print them.

    For the sake of learning, and to develop an extendable web app, I'd like to follow the proper i18n path, though I only need to define one (english) set of messages now.

    So the locales should all default to english when they don't find their own resources (which I'm yet to define).

    I've never used any of the i18n functionality of Java. And the spring docs assume that I have this knowledge.

    Could someone just give me a gental nudge in the right direction?

    I've defined a messageSource in my dispatcher-servlet.xml webapp context. I have a validator which produces a BindingResult object with a rejected field "username", with code "username.taken". I can generate the default message.

    Now I just need to get the error message from the errormessages.properties file in my view.

    How do I resolve an error code to a message?

    <bean id="messageSource"
          class="org.springframework.context.support.ResourceBundleMessageSource">
      <property name="basenames">
        <list>
          <value>errormessages</value>
        </list>
      </property>
    </bean>
    
  • David Parks
    David Parks over 13 years
    Great answer, thanks so much for that!!I guess my more pressing concern is going from the field error, which produces something like 4 error codes, and thus picking between which of the 4 error codes (or the default message) should be chosen and presented in the resulting page. But I posted another more specific question to that extent: stackoverflow.com/questions/4202437/… Thank you for this response, it's been very helpful also!