Take a look at the java.util.ResourceBundle class, mainly the getBundle() method. (You can use this or implement a similar mechanism yourself.)
Basically, you have a hierarchy of locales, and whenever the locale is not specifically supported, you return to the parent language. In your case, "ja_JP" (in Java notation) has the parent language "ja" , which in turn has the parent language "" .
Since most Japanese pages are not specific to Japan, you usually do all of the Japanese translation for ja , and only when something special is valid only for Japanese users in Japan, then optionally ja_JP . Then you also have no problem if any user sends jp_US , since he uses Japanese in the USA.
If you want to use the Java ResourceBundle mechanism only to indicate for which locales we have data, you can create (for example) these (empty) files:
- MyLocale.properties - matches the Locale ""
- MyLocale_de.properties - corresponds to "de" Locale (German)
- MyLocale_en.properties - Corresponds to "ru" Locale (English)
- MyLocale_ja.properties - matches "ja" Locale (Japanese)
Then in your program you will write
Locale rLocale = request.getLocale(); ResourceBundle bundle = ResourceBundle.getBundle("MyLocale", rLocale); Locale selectedLocale = bundle.getLocale();
Now, selectedLocale is definitely one of "", "de", "en", "jp", no matter what rLocale language was. For example, for "en", "en_GB", "en_US" in all cases, "en" will be selected, "ja" and "ja_JP" will result in "ja", while "de_DE" and "de_AT" will both result " de "and" it_IT "," eo "and most other locales will result in" ".
"The correct Java way": You will not ask your package about your locale, but just use the package as a ResourceBundle using localized resources. So, when you need some text, you do
String text = bundle.getText("greeting.hello");
and then print the text. Sometimes you have to use MessageFormat to format text with values inserted (or Formatter). (Then your property files would not be empty, of course, but they contain the following lines:
greeting.hello = Hello World!
(in a file in English)
greeting.hello = Hallo Welt!
(in the German file)
Please note that often the browser sends not only one Locale code, but also a list of preferred ones. Thus, you actually have to do this “search package” for each of these codes and transfer the first one that returns something else than “and return to” “only when the desired language is not requested. (For example , my browser sends "eo", "de_DE", "de", "en". Since most websites do not support Esperanto, they return to German (if available, and the selection is correct) or the default language (if they look only at the first record)).