Expert Spring MVC and Web Flow

(Dana P.) #1
<bean id="setLocaleController"
class="com.apress.expertspringmvc.chap4.SetLocaleController">
<property name="localeResolver" ref="localeResolver" />
</bean>

</beans>

There are situations where simple Dependency Injection won’t work, such as when Spring
doesn’t manage the life cycle of the handler object. For instance, the HandlerAdapterinterface
was created to allow any request handler to be easily integrated into the DispatcherServlet. In
cases such as these, the DispatcherServletplaces some of the framework objects, such as the
LocaleResolver, into the servlet request as request scoped attributes. This allows for any
object handling the HttpServlerRequestto be able to access the LocaleResolver.
To conveniently access the resolver without Dependency Injection, use the org.
springframework.web.servlet.support.RequestContextUtilsclass and its helpful
getLocaleResolver()method. This utility method encapsulates the knowledge of where
the LocaleResolveris placed in the request scope, making retrieval safer for the client. The
Controllercan be modified as shown in Listing 5-34.

Listing 5-34.RequestContextUtils.getLocaleResolver Example

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest req,
HttpServletResponse res) throws Exception {
String language = req.getParameter("language");
Locale locale = StringUtils.parseLocaleString(language);
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(req);
localeResolver.setLocale(req, res, locale);
return new ModelAndView("setLocaleSuccess");
}

This class no longer needs the setLocaleResolver()method, as Dependency Injection is
no longer used.
Which method should you use? Using Dependency Injection is always easier to test than
using RequestContextUtils, so the DI solution is preferable.
You have now seen the LocaleResolverinterface and the different options of interacting
with it. How the Locale, once it is set, affects the i18n features will be covered in Chapters 7
and 9. It’s time now to look in detail at the different implementations of LocaleResolver.

AcceptHeaderLocaleResolver
The DispatcherServletwill default to the org.springframework.web.servlet.i18n.
AcceptHeaderLocaleResolverclass if no other LocaleResolvers are specified in the
ApplicationContext. This implementation simply delegates to the HttpServletRequest’s
getLocale()method, thus obeying the Accept-Language HTTP header. Because the
header originates from the client, there is no way to change the Locale, so the
AcceptHeaderLocaleResolverwill throw an exception if setLocale()is called.
There is no need to specify this class in your ApplicationContext, as the DispatcherServlet
will create it if no implementations can be found.

104 CHAPTER 5 ■THE PROCESSING PIPELINE

Free download pdf