Martin
Martin

Reputation: 51

How can I switch language dynamically in spring mvc?

I want to switch language between English and Chinese, so I create two language files:

messages_en.properties messages_zh.properties

and in jsp file, my code as below:

<c:choose>
<c:when test="${language=='en'}">
    <a href='<c:url value="/language?language=zh" />'>
    <i class='glyphicon glyphicon-asterisk'></i>&nbsp;
        <s:message code="label.language" />
    </a>
</c:when>
<c:otherwise>
    <a href='<c:url value="/language?language=en" />'>
    <i class='glyphicon glyphicon-asterisk'></i>&nbsp;
        <s:message code="label.language" />
    </a>
</c:otherwise>

and in controller file, my code as below:

@RequestMapping(value = { "/language" }, method = RequestMethod.GET)
public String switchLanguage(@RequestParam("language") String language,
        ModelMap model) {
    Locale currentLocale = null;

    if ("zh".equals(language)) {
        currentLocale = new Locale("zh", "CN");
    } else if ("en".equals(language)) {
        currentLocale = new Locale("en", "US");
    }
    model.put("language", currentLocale.getLanguage());

    return "/book/index";
}

and in .xml file, i config MessageSource as below:

 <bean id="messageSource" 
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:language/messages"/>
    <property name="defaultEncoding" value="UTF-8"/>
</bean>

How can I change my controller action code to switch language dynamically?

Thanks.

Upvotes: 2

Views: 7914

Answers (2)

David Lavender
David Lavender

Reputation: 8311

Have a look at the org.springframework.web.servlet.i18n.LocaleChangeInterceptor bean.

It looks like that is what you are missing, or trying to write yourself. It picks up the ?language=en URL parameter and changes this user's session locale for you.

A good tutorial here

Upvotes: 1

Ria
Ria

Reputation: 2100

You can use

Locale locale = Locale.forLanguageTag(language);

to get the right Locale. language can be something like "en" or "en_US". Problem is that you only get the language from your requestParameter and you know by definition which country to use.

I'd create a map for this containing the languages as Keys and the countries as values. Thus you can do

String languageCountry = language + "_" + myCountryMap.get(language); // returns "US"
Locale locale = Locale.forLanguageTag(languageCountry );

Upvotes: 1

Related Questions