Expert Spring MVC and Web Flow

(Dana P.) #1
CookieLocaleResolver
The CookieLocaleResolversets and retrieves the Localeobject via a browser cookie. This strat-
egy is useful when the application does not support sessions and the state must be kept client
side.
Simply declare this class in your ApplicationContextto use it. Note that you can configure
the name of the cookie if you choose, but the class provides a sensible default. If you wish to
clear the Localecookie, simply call setLocale()and pass in a nulllocale.
Listing 5-36 contains a sample bean definition for a CookieLocaleResolver.

Listing 5-36.CookieLocaleResolver Bean Definition

<?xml version="1.0"?>
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="cookieLocaleResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />

</beans>

■NoteIf there is no Localecookie present, this class will fall back to ServletRequest’s getLocale()
method. ThegetLocale()method returns the client’s preferred Locale,as dictated by the Accept-Language
HTTP header. If the client did not specify an Accept-Language header, the method returns the default Localeof
the server.

SessionLocaleResolver
The SessionLocaleResolverstores the user’s Localeinside the HttpSessionobject, and it sup-
ports both retrieval and modification. It offers a nice alternative to storing the locale state in a
cookie. As with the CookieLocaleResolver, if no Localeis found in the session, this class will
fall back to the getLocale()method of HttpServletRequest.
This implementation (see Listing 5-37) is as easy to declare as the CookieLocaleResolver.

Listing 5-37.SessionLocaleResolver Bean

<?xml version="1.0"?>
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

106 CHAPTER 5 ■THE PROCESSING PIPELINE

Free download pdf