When you need your application to be internationalized, you want all messages displayed to the user to be in the language of their locale.
Java has a class called java.util.ResourceBundle which helps you do this.
You can create property files with extensions which correspond to various locales.
For example, I can have greetings_en_US.properties and greetings_fr_CA.properties.
The first contains greetings to be displayed to english users from US. The second is for french users from Canada.
Inside the first, I will have a key-value pair like:
greet="Hello World!"
In the second, I wil have:
greet="Bonjour"
In my application, I will have the code:
ResourceBundle res = ResourceBundle.getBundle("greetings");
String greetStr = res.getString("greet");
Java's ResourceBundle class automatically picks the correct property file based on the current locale. If it is a HTTP request, the browser will send the locale of the user, and that will determine which property file will be picked up.
Property files which are designed to be used by ResourceBundle class are themselves called "resource bundles".
Let us modify our project from the previous post to use resource bundles.
In the /src/main/resources folder, create two files:
greetings_en_US.properties and greetings_fr_CA.properties
In the first, type:
greet="Hello World!"
In the second, type:
greet="Bonjour"
Now update your index.jsp to:
<html>
<head>
<%@ page import="java.util.ResourceBundle" %>
</head>
<body>
<% ResourceBundle res = ResourceBundle.getBundle("greetings"); %>
<h2><%= res.getString("greet")%></h2>
</body>
</html>
R-click on the project in Eclipse navigator and select Run As-->Maven install.
I am assuming you are using the cargo plugin to deploy the war, as described in this post.
Then point your browser to:
http://localhost:8080/HelloWorldWARArch/
You will see "Hello World!" if you are in the US.
Now, let us force our code to change locale.
Change your index.jsp to:
<html>
<head>
<%@ page import="java.util.ResourceBundle" %>
<%@ page import="java.util.Locale" %>
</head>
<body>
<% ResourceBundle res = ResourceBundle.getBundle("greetings",new Locale("fr","CA")); %>
<h2><%= res.getString("greet")%></h2>
</body>
</html>
Now if you build and deploy your application, you will see "Bonjour!"
You can have as many resource bundles as you want to reflect different locales.
If a resource bundle for a given locale is not found, the default resource bundle (i.e. the one which has no locale specification - greetings.properties) will be used.
No comments:
Post a Comment