URL-based Locale
Join the DZone community and get the full member experience.
Join For FreeWe should assume that users will not always be browsing from a
comfortable location (pronounce: home / work). Even if they do, every
now and then I have guests at home that do not speak Spanish at all. Try
opening the Google home page in a cybercafé in Germany or Finland to
see what I mean. It may be convenient, but the browser language is often
not good enough for the real world.
If your application supports multiple languages you should give the user
an option to change the locale without messing with the browser
settings. Specifically, don't force the user to find the settings in a
foreign language and foreign browser, and don't assume that he/she is
allowed to change them.
There are a couple of possible implementations for this:
- Store the locale in the user session: this solution does not persist the locale during browser restarts and implies an existing session for each anonymous user, which is not always an option.
- Store the locale in the user settings (database): this is possible only if you do not have anonymous users.
- Store the locale in a browser cookie.
- Store the locale in the URL
Implementing this in your own application is easy: Loom has PrefixLocaleResolver, but with other frameworks you may just use your own web Filter to resolve the user locale as well. Naïve version follows:
public class LocaleResolverFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
String serverName = request.getServerName();
String lang = StringUtils.substringBefore(serverName, ".");
if (lang.length() != 2) {
lang = "en";
}
final Locale locale = new Locale(lang);
chain.doFilter(new HttpServletRequestWrapper(request) {
@Override
public Locale getLocale() {
return locale;
}
}, response);
}
@Override
public void destroy() {
// empty
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// empty
}
}
In order to test this, you should add this entry to your hosts file:
127.0.0.1 localhost es.localhost en.localhost www.localhost
Me, I find it funny to think about my "English localhost" :) If you have any interesting ways of detecting your user language, I would love to hear it!
From http://icoloma.blogspot.com/2010/08/url-based-locale.html
Opinions expressed by DZone contributors are their own.
Comments