3

On my JSF 2.1 Application with JDK 7, I searched for a solution to provide my users the possibility to save their preferred language. So, on the next login the language should received from the Database and replaced by the language from the default (Browser). My only problem is now, how to save the java.util.Locale in my database? After hours of googling I found a new functionality inside of JDK 7 that is the "forLanguageTag Factory Method". This method returns a Locale and only needs for that a IETF BCP 47 standard string.

This sounds really simple and great for me. But how can I get this "IETF BCP 47 standard"-String from an existing locale? I looked in the API but found nothing that is comparable to the "IETF BCP 47 standard".

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Cruel
  • 75
  • 1
  • 4

2 Answers2

8

Consider Locale.toLanguageTag:

Returns a well-formed IETF BCP 47 language tag representing [a] locale.

Example usage:

String expectedTag = "en-US";
Locale locale = Locale.forLanguageTag( expectedTag );
String actualTag = locale.toLanguageTag();
Assert.assertEquals( expectedTag, actualTag );

Note: There are some restrictions as mentioned in the javadocs.

btiernay
  • 7,873
  • 5
  • 42
  • 48
4

If you're just interested in the language, simply use Locale.getLanguage() to transform a locale into a String, and new Locale(String language) to transform the String into a Locale.

If you want to store the whole Locale, use Locale.toString(), and a custom method that splits on _ to transform the string into the three parts of a Locale.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255