Dreamer
Dreamer

Reputation: 7549

Autowire HttpServletRequest? To solve Locale?

My current project requires a customized "System date", which means a system date and it's format defined in the i18n properties file. But the class dealing with it is a general utility class but not within the web layer. However the locale(to work out the date format) has to be retrieved from a HttpServletRequest object. I am thinking autowire a HttpServletRequest instance to that utility class. It seems break the design pattern but I guess it is piratical. However it doesn't work. So what is wrong with that and is there any better way to solve the Locale in any other layers in Spring?

Thanks in advance.

Upvotes: 0

Views: 1084

Answers (2)

Japan Trivedi
Japan Trivedi

Reputation: 4483

I prefer you to use the Spring Framework's SessionLocaleResolver. It will change and store the locale in the session and hence you can get that at any point of code in the application.

Please refer the below mentioned configuration for the same. And also read the Spring Documentation for the same for the better understanding.

    <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>

Hope this helps you. Cheers.

Upvotes: 0

pap
pap

Reputation: 27614

Wouldn't it be a lot more elegant to simply overload the utility-class to accept a Locale as parameter on the affected methods. Then you can retrieve the locale in your controller and pass it down to the utility.

Upvotes: 2

Related Questions