【问题标题】:Spring MVC Locale change doesn't workSpring MVC 语言环境更改不起作用
【发布时间】:2014-04-18 19:24:53
【问题描述】:

在我的应用程序中,我定义了以下 bean,但是当我尝试使用参数 ex 更改语言环境时:?lang=es 它对我不起作用,并且显示的是 CookieLocaleResolver 中定义的默认语言环境,即英语。

这是我的 bean 类:

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

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

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

<bean
    class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
    <property name="interceptors">
        <list>
            <ref bean="localeChangeInterceptor" />
        </list>
    </property>
</bean>

我想要实现的是使用参数更改语言并将其保存在与该参数相关的 cookie 中,以便进一步请求区域设置是新的区域设置语言!

我也不想使用下面的类,因为它已经被弃用了:

org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping

我的声明性 bean 实现有什么问题?

【问题讨论】:

    标签: java spring jakarta-ee spring-mvc


    【解决方案1】:

    我相信你应该这样定义interceptor

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="resources/i18n/messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**" />
            <bean id="localeChangeInterceptor"
                class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
                <property name="paramName" value="lang" />
            </bean>
        </mvc:interceptor>
    </mvc:interceptors>
    
    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="cookieName" value="lang" />
        <property name="defaultLocale" value="en" />
    </bean>
    

    MVC 命名空间是这样定义的:

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

    确保使用正确的 xsd 版本。

    【讨论】:

    • spring 中的“mvc”命名空间定义是什么?你能在这里发帖,以便我可以把它放在我的应用程序上下文定义中吗?
    • 已编辑后,请记住为您的 xsd 架构使用正确的版本
    • 是的,让我看看你的解决方案!
    • 您的解决方案很有魅力!你能帮我解答第二个问题吗? “有没有可能我有两种方法可以在我的应用程序中更改语言环境???”
    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 2015-08-03
    • 2014-09-15
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多