0

On my local machine. In my jsp I am using

Locale.getDefault();

it prints India as country name

In spring controller I use

public @ResponseBody HashMap searchOffer(Locale locale){
    locale.getDisplayCountry()
}

It display 'United State`. Why? two different Country on same machine..

Which one should I use to read the the user's locale?

Manish Kumar
  • 10,214
  • 25
  • 77
  • 147
  • `Locale.getDefault()` reports the JVM/System default. `locale` isn't known to us. Where do you get it from? – mabi Apr 15 '14 at 08:14
  • i am running this app in my local machine – Manish Kumar Apr 15 '14 at 08:15
  • Sure, but we don't see how `locale` is instantiated. How do you initialize the variable? – mabi Apr 15 '14 at 08:18
  • The default locale for the JVM can be specified (overwritten) using `-Duser.locale` when starting Java. Maybe the startup script for your servlet container specifies such an option. –  Apr 15 '14 at 08:23
  • 1
    I just want to know the country name of the user who is requesting jsp page – Manish Kumar Apr 15 '14 at 08:28
  • 2
    AFAIK this locale is derived from the `Accept-Language` HTTP header. You sure your browser doesn't send "en-US" as the first choice? – mabi Apr 15 '14 at 08:32
  • Yah in firebug I can see `Accept-Language en-us,en;q=0.5` under `Request Headers` – Manish Kumar Apr 15 '14 at 08:34

1 Answers1

0

While I have no knowledge of the Spring Framework, the way to figure out a per request Locale object without session information is usually by looking at the Accept-Language HTTP header. Which isn't a very good choice because it misleads people to think they'll acquire the user's whereabouts.

As the link above states, you probably want to give the user a way to override your first guess by storing a preference option, looking at the request IP (using a geocoding database like in this question) or something else. Where "storing a preference option" is the only thing that requires the notion of a "returning user". Most common choices are storing the Locale object in the user's session. You can read about the (spring specific) list of options in the manual.

To answer the question: the static method Locale.getDefault() will report the JVM "fallback" locale, which is usually derived from the system the JVM is running on (or as @a_horse_with_no_name points out, can be overriden with -Duser.locale).

Community
  • 1
  • 1
mabi
  • 5,279
  • 2
  • 43
  • 78