How to Detect the Client's Preferred Languages
Browsers send a list of the user's preferred languages in the Accept-Language header field. The Servlet API helps you using it with two methods in the ServletRequest:
- getLocale returns the client's preferred language
- getLocales returns all language the client accepts in order of preference
This example greets a visitor either in German or English, depending on what the user prefers:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Locales supported by the servlet:
List<Locale> supported = Arrays.asList(Locale.ENGLISH, Locale.GERMAN);
// Locales supported by the client (ordered by preference):
List<Locale> accepted = Collections.list(request.getLocales());
// determine best locale for the client
Locale locale = Locale.ENGLISH; // fallback default
for (Locale a: accepted)
for (Locale s: supported)
if (s.equals(a)) {
locale = a;
break;
}
response.setContentType("text/plain; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setLocale(locale); // declare content language
PrintWriter writer = response.getWriter();
if (locale.equals(Locale.ENGLISH))
writer.println("Hello, visitor!");
else
writer.println("Hallo, Besucher!");
else
assert false; // can't happen
}

