Expert Spring MVC and Web Flow

(Dana P.) #1
This action is often a manual operation, helped tremendously by the chosen strategy,
because many users and clients cannot be trusted to set their browser’s language preferences
correctly. In other words, you probably can’t trust that the Accept-Language HTTP header is
correctly configured all the time.

■NoteThe DispatcherServletdoes not support chaining LocaleResolvers, so you are allowed to
choose only one implementation.

Setting a Locale
Your application’s design will dictate when you should call setLocale, normally in response to
some user action. For example, the application might provide a page with language choices,
and the user will be able to choose one and submit it back to the server.
In one possible implementation, you would create a Controllerthat delegates to a
LocaleResolverin order to store the user’s chosen Locale. Listings 5-30 and 5-31 show you
how to do this.

Listing 5-30.HTML Form, Choosing Language

<form action="setLocale" method="post">
<p>
Language: <select name="language">
<option value="en">English</option>
<option value="de">German</option>
</select>
</p>
<p>
<input type="submit" />
</p>
</form>

Listing 5-31.SetLocaleController

public class SetLocaleController extends AbstractController {

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest req,
HttpServletResponse res) throws Exception {
String language = req.getParameter("language");
Locale locale = StringUtils.parseLocaleString(language);

// How did we get a reference to the localeResolver?
// See Listings 5-32 and 5-34 for the two strategies
// for obtaining a reference
// to this localeResolver instance

102 CHAPTER 5 ■THE PROCESSING PIPELINE

Free download pdf