at.
at.

Reputation: 52570

How to get visitor's locale in JSP using Spring 3's SessionLocaleResolver

I need to get a visitor's locale in my JSP pages so that I can properly display a drop down menu with a list of languages and have the selected language according to their current locale. Normally I might do something like ${pageContext.request.locale}.

The problem, I think, is that will only give me the locale according to the user's request headers (what the browser sends). But the user may have changed their language/locale, so I need to use Spring's mechanism which looks at the session too:

RequestContextUtils.getLocale(request).toString();

But then it's not so easy to access that in a JSP page and have JSP code work with it.

Or is there another easier mechanism to display a drop down menu of languages to a user? Does Spring store the current locale in an object easily accessible from JSP?

Upvotes: 9

Views: 10742

Answers (3)

Jan Thomä
Jan Thomä

Reputation: 13632

For us

${pageContext.response.locale}

did the trick. This property follows what has been set up by Spring's locale resolver.

Upvotes: 28

Bhavesh
Bhavesh

Reputation: 11

One line solution..

RequestContextUtils.getLocale(request)

Upvotes: 1

Peter
Peter

Reputation: 5224

As you use the SessionLocaleResolver the current locale is stored in the session using an attribute name specified in the SessionLocaleResolver Class. The reference to the SessionLocaleResolver is stored in the request using another attribute name (org.springframework.web.servlet.DispatcherServlet#LOCALE_RESOLVER_BEAN_NAME).

I don't see an easy way to get the locale directly within the jsp page without using java code.

I would fetch the current locale and create the list of selectable languages in the controller and add this to the model.

This makes the code testable and moves java code from the jsp into the controller.

Upvotes: 2

Related Questions