Java – detect browser language in java

browserjava

I had problem in detecting the users' preferred browser language.

i found out that navigator object properties only detects system related language. the .userLanguage detects local language of the user's pc,or the one used in the task bar,and being set via ControlPanel>Regional&LanguageOptions, then the .systemLanguage detects the OS language, then the .browserLanguage detects the default browser language of the system. so none of these stuffs would help me.

what I need is to detect the user's preferred browser language that is being set via Tools>InternetOptions

Is there any way to do that using Java?

Hope somebody out there could help me

Best Answer

If you can access the HttpServletRequest object, it is pretty easy. Let's say, you are in a servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
        Enumeration locales = request.getLocales();
/**
*You can get the first one matches your supported local like below
*/
        while (locales.hasMoreElements()) {
             Locale locale = (Locale) locales.nextElement();
             if (supportedLanguages.contains(locale)) {
                 requestLocale = locale;
                 break;
             }
        }
       super.doPost(request, response);
   }

If you are talking about detecting browser language at client side. I'd rather suggest you to us JS to get the browser language, and you can call the js in your Java code. BTW, I tested it on my chrome:

var type=navigator.appName
if (type=="Netscape"){
var lang = navigator.language
}
else{
var lang = navigator.userLanguage
}