Sunday, July 29, 2007

Make Your Webapp Speak French

Whenever you create a web application that has global implications, you always need to internationalize it. This means it should be able to interact with the user in their browser or selected language. Our latest requirement for the timecard utility is for usability in both English and French. It demonstrates how to internationalize a JSF application using message bundles.

Message bundles are resources provided through properties files. The java.util.ResourceBundle is a convenient class used to access resources availed to the application. Properties files hold key/value pairs of strings.
Creating internationalization property files is typically a manual process: you identify what text on the UI needs to be in alternative languages, create key/value pairs for them in a properties file, then copy the whole set to other properties files - providing translated text in those files. As you can already tell, to change a single text element, you need to update all other files as well. Also, if you change the key, you need to manually update the classes that use that key directly. NetBeans 6.0 does not provide context-sensitive code completion between properties files and Java classes.

To implement the requirement specified, you create two property files - one for English and the other for French, then populate them accordingly. So, if I put in the title = Timecard Utility, then I need to also put in the title = Utilité de Carte de Pointage. The application will only look for the title key in the appropriate properties file and print out its string value. In the JSP, you'd need to call the french properties file with:
<f:loadBundle basename="com.strive.research.intl.french" var="lang"/>
(assuming it is in com/strive/research/intl package).

While this strategy works well, it doesn't update strings generated in the application itself and the propery file to use cannot be set dynamically. The solution is to use your managed bean to set which file the JSP should used. To do this, you create an additional variable in the managed bean that can be set based on the user's selection. When the selection is made, an appropriate locale and properties file are set before the page is redisplayed. To be able to print language-appropriate dates and times, you'd need to take advantage of the java.util.Locale class. The image below shows the result of selecting the French language option.

The big advantage of this implementation is that you don't have to change much code to support additional languages. Also, text changes can be made without having to recompile the application.
JSF also provides a mechanism for automatically applying the correct language based on the browser language. You'd need to set that up in faces-config.xml.

Brandon, let me know if you need the source code for this - pretty minor changes - and I'll send it to you. This application is growing bigger and bigger codebase-wise.

No comments: