【问题标题】:Autowire HttpServletRequest? To solve Locale?自动装配 HttpServletRequest?解决语言环境?
【发布时间】:2012-05-16 01:48:35
【问题描述】:

我当前的项目需要自定义的“系统日期”,这意味着系统日期及其格式在 i18n 属性文件中定义。但处理它的类是通用实用程序类,但不在 Web 层内。但是,必须从 HttpServletRequest 对象中检索语言环境(计算日期格式)。我正在考虑将 HttpServletRequest 实例自动连接到该实用程序类。它似乎打破了设计模式,但我想它是盗版的。但是它不起作用。那么这有什么问题,有没有更好的方法来解决 Spring 中任何其他层中的 Locale 问题?

提前致谢。

【问题讨论】:

    标签: spring servlets spring-mvc locale autowired


    【解决方案1】:

    简单地重载实用程序类以接受Locale 作为受影响方法的参数不是更优雅吗?然后,您可以在控制器中检索语言环境并将其传递给实用程序。

    【讨论】:

    • 感谢您的快速回答,爸爸。这里的问题是系统日期不是从明确的“请求”中检索到的,它应该在用户在浏览器中点击网络应用程序的 url 时显示在索引页面上。我知道我们可以根据任何 url 模式创建一个控制器,但是我们可以从“/”请求中获得一个明确的 HttpServletRequest 实例吗?谢谢。
    【解决方案2】:

    我更喜欢你使用 Spring Framework 的 SessionLocaleResolver。它将更改并存储会话中的语言环境,因此您可以在应用程序中的任何代码点获取它。

    请参考下面提到的配置。并阅读 Spring Documentation 以获得更好的理解。

        <mvc:interceptors>
            <ref bean="localeChangeInterceptor"/>
        </mvc:interceptors>
    
        <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.SessionLocaleResolver">
            <property name="defaultLocale" value="en"/>
        </bean>
    
        <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            <property name="basenames">
            <list>
                <value>/WEB-INF/i18n/labels</value>
                <value>/WEB-INF/i18n/messages</value>
            </list>
            </property>
            <property name="defaultEncoding" value="UTF-8"/>
        </bean>
    

    希望这对您有所帮助。干杯。

    【讨论】:

      猜你喜欢
      • 2018-08-15
      • 1970-01-01
      • 2014-07-08
      • 2022-01-15
      • 2015-10-20
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2022-12-10
      相关资源
      最近更新 更多