Saturday, July 19, 2008

Advanced J2EE Concepts - Implementing Internationalization in Struts

Advanced J2EE Concepts - Internationalization in Struts

How is ‘Internationalization’ implemented in struts?

Default Internationalization (Detected based on Browser's settings):

Internationalization is an important concept of making the application to be compatible with different geographical location and user-friendly with respect to their location by means of providing the information in their preferred language.

In struts, it can be done quite easily. The application resource file name can be extended with underscore followed by locale.

For example ,

When your application contains the file “ApplicationResource_en.properties”, it would mean that it supports english language. When another file “ApplicationResource_fr.properties” exists, it would mean the localization for ‘French’.

The selection of file and the content is done and decided automatically by struts. When the browser’s setting is found with French settings, then struts automatically retrieves the value for the specific key from the appropriate resource file. Similarly you can add multiple property files for various locale.

But please remember that you can have one property file name with different extensions like _en, _fr, _de, etc., If they differ, the internationalization will not work. Also that only one file (one time), is specified in struts-config.xml. Each property file must have the same key with different values as follows:

In ApplicationResources.properties_en, you specify mainpage.welcome=Hi, You are welcome..

In ApplicationResources.properties_fr, you specify mainpage.welcome=< message in French >

Programmatic implementation of Internationalization (By manual selection)

The localization can even be done programmatically by placing ‘Locale’ object in session.
session.setAttribute("org.apache.struts.action.LOCALE", new Locale("fr"));

For example, You can create links one for each country's localization in the main page. Each link leads to an action class with different query string such as

<A HREF="setCountry?lang=en" > English <A>

<A HREF = "setCountry?lang=de"> German <A>

<A HREF="setCountry?lang=fr"> French <A>

When clicked, the action is called. Inside the action class you retrieve the lang parameter as follows

String lang = request.getParamter("lang");

if (lang.equals("fr"))

session.setAttribute("org.apache.struts.action.LOCALE", new Locale("fr"));

if (lang.equals("de"))
session.setAttribute("org.apache.struts.action.LOCALE", new Locale("de"));

-------------------------------------------------------------

Hope this explains the concept of internationalization. For any queries, write to me to swathikalakshmi@gmail.com. I would come with lot more of advanced concepts in blogs to come.

Regards

Swathika.

1 comment:

Soupboy said...

Hi,

i have one question. how do you handle the internationalization while storing the data?