Expert Spring MVC and Web Flow

(Dana P.) #1
localeResolver.setLocale(req, res, locale);

return new ModelAndView("setLocaleSuccess");
}

}


■Tip Spring MVC provides a LocaleChangeInterceptorthat performs the exact same operation as the
above example Controller.This interceptor is recommended, especially if many forms all have the same
locale request parameters.


Retrieving a LocaleResolver


Clearly you may use the LocaleResolverto set the locale, but what is the best way to obtain a
reference to the localeResolverfrom inside the Controller? There are at least two ways to get
the LocaleResolverobject, each with different advantages. Which way you choose will be up
to you.
The most obvious way to get the LocaleResolveris to rely on Dependency Injection.
The LocaleResolverinstance is a bean in the ApplicationContextlike all other objects in
the system, so Spring will be happy to set this object into your Controllervia DI for you. The
DispatcherServletwill recognize only one LocaleResolverin the ApplicationContext(it won’t
chain multiple resolvers of this type), so typically there will be only one instance in the appli-
cation. If you have defined a LocaleResolverin the context, consider altering your Controller
to allow for injection of the resource, as shown in Listings 5-32 and 5-33.


Listing 5-32.Adding a Setter Method for Dependency Injection


private LocaleResolver localeResolver;

public void setLocaleResolver(LocaleResolver localeResolver) {
this.localeResolver = localeResolver;
}

Listing 5-33.SetLocaleController ApplicationContext


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



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

CHAPTER 5 ■THE PROCESSING PIPELINE 103
Free download pdf