Teifi
Teifi

Reputation: 713

spring i18n LocaleResolver getLocale

dealing with spring i18n. I have defined two beans in spring-mvc.xml

<bean name="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang" />
</bean>

<bean name="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <property name="defaultLocale" value="en" />
</bean>

and two anchors in jsp to switch languages

<span>
    <a href="?lang=en">english</a>
    | 
    <ahref="?lang=zh">chinese</a>
</span>

I tried to get the parameter lang/locale at my controller and i18n the results before javascripts (because I want to i18n java script), but doesn't work.

request.getLocale().getDisplayName();
request.getParameter("lang");

how do I get the Locale at my controller? or any good idea to i18n java scripts?

Thanks in advance!

Upvotes: 0

Views: 7136

Answers (3)

weekens
weekens

Reputation: 8292

Have a look at Spring Web MVC parameter reference: http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-arguments

Supported method argument types
...
java.util.Locale for the current request locale, determined by the most specific locale resolver available, in effect, the configured LocaleResolver in a Servlet environment.

This means that you can simply use java.util.Locale argument in your Controller method, and a currently-resolved locale will be assigned to this argument by Spring MVC:

@RequestMapping(value = "/{viewName}", method = GET)
public String handle(@PathVariable String viewName, Locale locale) {
    return "info/" + locale.getLanguage() + '/' + viewName;
}

Upvotes: 1

Carlos AG
Carlos AG

Reputation: 1087

And if you want to change to another Locale, in Java, you can use:

String anotherLocale="es"; RequestContextUtils.getLocaleResolver(request).setLocale(request,response, anotherLocale);

Upvotes: 1

Teifi
Teifi

Reputation: 713

@Controller
public class MyController{
    @RequestMapping(value = "/test")
    public test(HttpServletRequest request, HttpServletResponse response){
        Locale locale = RequestContextUtils.getLocale(request);
        System.out.println("Locale >>> " + locale);
    }
}

result:

Locale >>> en

Upvotes: 0

Related Questions