Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Setting up locale

I've setup Spring as specified in the following guide: http://www.springbyexample.org/examples/basic-webapp-internationalization-spring-config.html

If I was to append ?locale=fr, for example, to the end of an URL the locale will change to French.

However, in my case, I want to set the locale when the user logs in as this information is associated with their profile. I've tried to use localeResolver.setLocale(request, response, new Locale("fr")) (where localeResolver is an instance of SessionLocaleResolver) to specify the locale however this doesn't have any effect.

Any idea what I'm doing wrong? Am I approaching this issue in the correct way?

like image 697
NRaf Avatar asked Jun 22 '11 02:06

NRaf


1 Answers

localeResolver.setLocale works fine for me, try something like this:

applicationContext

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
    p:basename="messages/messages" p:fallbackToSystemLocale="false" />

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />

my_page.jsp

<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<html>
    <body>
        <p><spring:message code="my.message"/></p>  
    </body>
</html>

\src\main\resources\messages\messages.properties

my.message=Message (default language)

\src\main\resources\messages\messages_en.properties

my.message=Message in English

\src\main\resources\messages\messages_fr.properties

my.message=Message in French

Controller

@Controller
@RequestMapping("/")
public class SampleController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String welcome(HttpServletRequest request, HttpServletResponse response) {
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        localeResolver.setLocale(request, response, StringUtils.parseLocaleString("fr"));
        return "my_page";
    }
}

With this code I get "Message in French", if I change "fr" to "en" I get "Message in English", and without setLocale call I get "Message (default language)". Changing StringUtils.parseLocaleString("fr") to new Locale("fr") gives the same results.

like image 130
John29 Avatar answered Sep 28 '22 16:09

John29