开发者

How do I get the currently used locale from Spring MVC?

I have the following form.

<form id="langForm" action="" method="get">
    <select name="lang" id="lang" class="styled" onchange="this.form.submit();">
        <option value="pl" ${param.lang == 'pl' ? 'selected' : ''} >PL</option>
        <option value="en" ${param.lang == 'en' ? 'selected' : ''} >EN</option>
    </select>
</form>

Spring MVC sets the language parameter and takes care about i18n/l10n. I would like to change the ${p开发者_如何学JAVAaram.lang} to let it obtain the current user language from session by Spring MVC, because the lang parameter is not necessarily present in every request. How can I achieve this?


Add the fallowing in your xml configuration:

...

<mvc:interceptors>
        <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" />
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
            p:paramName="lang" />
    </mvc:interceptors>

<bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver"
        id="localeResolver" p:cookieName="locale" />
...

Replace you code by:

<form id="langForm" action="" method="get">
    <select name="lang" id="lang" class="styled" onchange="this.form.submit();">
        <option value="pl">PL</option>
        <option value="en">EN</option>
    </select>
</form>

With this configuration the locale selected wil be save in cookies browser.

don't forget namespaces at the begin of file in tag : xmlns:mvc="http://www.springframework.org/schema/mvc" and

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

tutorial here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜