0% found this document useful (0 votes)
41 views15 pages

Creating An Internationalized Application: June 2006 (Revision Number: V2.1-2)

Sun Studio

Uploaded by

nyellutla
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views15 pages

Creating An Internationalized Application: June 2006 (Revision Number: V2.1-2)

Sun Studio

Uploaded by

nyellutla
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Creating an Internationalized Application

June 2006 [Revision number: V2.1-2]


Copyright 2006 Sun Microsystems, Inc.

This tutorial explains how to internationalize a web application using the Sun Java Studio Creator application development tool (or IDE). The application described in this tutorial enables a client browser to set the application's locale and character encoding at runtime. This capability is useful when your application must support multiple languages, different encodings of the same language, or legacy encodings. The application responds to user choice of one of four locales and three character encodings. After the user chooses a locale and encoding, the application server sends text for display in that encoding and accepts text entered by the user in the same encoding. Contents - Setting Up Your System Designing the User Interface - Providing Action Methods - Creating Properties Bundle - Testing Your Application Example used in this tutorial demonstrating_i18n_ex.zip

Setting Up Your System


Before working through this tutorial, setup your system so that the following languages and the fonts needed to display them are present: English, Russian, Japanese, and Simplified Chinese. The process for installing languages and fonts depends on the platform on which you are working. Please consult your system documentation for instructions.

Designing the User Interface


You will use Grid Panel components to organize the user interface elements and help to isolate the layout from differences among browsers and operating systems at runtime. Grid Panel components are especially useful in internationalized applicationswhen you use Grid Panel components, page layout is less affected by differences in string length for various languages.

1. Create a new web application project and name it HelloBundledWorld. 2. From the Components Palette, choose the 14 components shown in the following table and drag them onto the page in the Visual Designer. As you drag each component on the page, change its id property to the value shown in the third column of the table. Table 1: Components to Place on Page Quantity Component Type 3 Layout > Grid Panel 6 Basic > Static Text 2 1 1 1 Basic > Label Basic > Button Basic > Text Field Basic > Drop Down List ID Properties gridLarge, gridUpperRight, gridCenterRight helloText, chosenOption, chosenIndex, chosenLocale, chosenEncoding, youEnteredDisplay enterTextLabel, youEnteredLabel submitButton textEntry localeDropDown

Placement of the components is not critical at the moment, but your page should look something like the following figure:

Figure 1: Initial Page Layout 3. Select each Grid Panel component in turn and, in the Properties window, change each of their columns properties to 2 and each of their rules properties to all. Displaying the rule lines will help you adjust the layout. You will now arrange the components into their final configuration. The easiest way to do so is to drag their names into the Outline window. 4. In the Outline window, expand the page1 > html1 > body1 > form1 node if it is not already expanded. Drag the component names to organize them as shown in the following figure.

Figure 2: Organizing Page Layout in Outline Window The page in the Visual Designer should now look something like the following figure.

Figure 3: Grid-Organized Page Layout 5. Select each Grid Panel component in the Outline window and change its rules property to none to remove the rule lines from the display, as shown in the following figure.

Figure 4: Adjusting Grid Panel Sizes 6. Select the Button component and, in the Appearance section of the Properties window, set the text property to Submit. 7. Select the Drop Down List component, right-click, and choose Auto-Submit on Change from the pop-up menu.

Providing Action Methods


You now edit the submit_action() method for the Button and the localeDropDown_processValueChange() method for the Drop Down List. 1. With Page1 displayed in the Visual Designer, double-click the Submit button. The IDE creates an action method for the Button component, opens the Java Editor, and places the editing cursor in the method. 2. Edit the submitButton_action() method to read as shown in the following code example: Code Example 1: submitButton Action Method public String submitButton_action() { // Get value of drop-down list and process it String str = this.localeDropDown.getValue().toString(); processLocaleChange(str); return null; }

You will fix the symbol not found error in the next section. 3. Return to the Visual Designer for the page and double-click the Drop Down List. The IDE creates a process value change method for the component, opens the Java Editor, and places the editing cursor in the method.

4. Edit the localeDropDown_processValueChange() method by adding the following code shown in bold. Code Example 2: Drop Down List Value Change Method public void localeDropDown_processValueChange(ValueChangeEvent event) { // Process new drop-down list value processLocaleChange((String)localeDropDown.getSelected()); }

Adding the processLocaleChange() Method Both of the methods you have just edited call the processLocaleChange() method. You now provide the method. 1. With Page1 displayed in the Java Editor, scroll to the beginning of the Page1 class and add three lines to define the variables index, encodings, and locales. The first five lines of the class should look like the code shown in the following code example. Code Example 3: Initializing index, encodings, and locales Variables public class Page1 extends AbstractPageBean { Creator-managed Component Definition private int index =-1; String[] encodings = {"UTF-8", "UTF-8", "Shift_JIS", "GB2312"}; String[] locales = {"en_US", "ru_RU", "ja_JP", "zh_CN"};

2. Scroll to the end of the file and insert the code shown in the following code sample just before the final closing brace (}). The processLocaleChange() method obtains the language and locale chosen by the user in the drop-down list, determines the first two characters and uses them to set the locale for rendering the JavaServer Faces components. Following the processLocaleChange() method, a String object is created to store the text entered by the user. Code Example 4: Code for processLocaleChange() Method private void processLocaleChange(String str) { chosenOption.setValue(":::"+str+":::"); String encString = str; // Get items from localeDropDown Option[] options = (Option[])localeDropDown.getItems(); String[] items = new String[options.length]; for (int i=0; i < options.length; i++) { items[i] = (String)options[i].getValue(); }

for (index = 0; index < items.length; index++) { if (items[index].startsWith(encString)) break; } chosenIndex.setValue("# "+index); if (index>=0&&index < items.length) { String locStr = locales[index]; Locale locale; if (locStr.length()>3) locale = new Locale(locStr.substring(0,2), locStr.substring(3,5)); else locale = new Locale(locStr.substring(0,2)); // Set the locale for rendering JSF components... FacesContext.getCurrentInstance().getViewRoot().setLocale(locale); // Save the encoding to use for this locale... getSessionBean1().setSessionEncoding(encodings[index]); chosenLocale.setValue(" = "+locStr);

chosenEncoding.setValue(encodings[index]); } else { index =-1; } } /** * Holds value of property capturedText. */ private String capturedText; /** * Getter for property capturedText. * @return Value of property capturedText. */ public String getCapturedText() { return this.capturedText; } /** * Setter for property capturedText. * @param capturedText New value of property capturedText. */ public void setCapturedText(String capturedText) { this.capturedText = capturedText; }

3. To eliminate errors due to unresolved symbols in the file, right-click in the Java Editor and choose Fix Imports from the pop-up menu. If a dialog box opens because more than one package contains a class name, choose the fully qualified name that contains com.sun.rave.web.ui.model.Option, as shown in the following figure, and click OK.

Figure 5: Choosing Class Names for Import Statement

One error remains on the line getSessionBean1().setSessionEncoding(encodings[index]);. You will fix this error later in the tutorial.

Adding Properties to the Session Bean You now add properties to the Session Bean to store the values of the Drop Down List component. 1. Open Page1 in the Visual Designer and view the contents of the project in the Outline window. Right-click the SessionBean1 node and choose Add > Property from the pop-up menu. The New Property Pattern dialog box opens. 2. In the New Property Pattern dialog box, type sessionEncoding as the property name and choose String as the type, as

shown in the following figure. Click OK.

Figure 6: New Property Pattern Dialog Box 3. Again, right-click the SessionBean1 node in the Outline window and choose Add > Property from the pop-up menu. In the New Property Pattern dialog box, type dropDownOptionsDescriptions as the property name and Option[] as the type, as shown in the following figure.Click OK.

Figure 7: Adding a New Property to the Session Bean

Adding Initialization Code to the Session Bean You will now add initialization code to the Session Bean that defines the choices shown to the user in the Drop Down List component. 1. In the Outline window, double-click the SessionBean1 node to open the SessionBean1.java file in the Java Editor. Locate the following comment lines in the init() method:

// Perform application initialization that must complete // *after* managed components are initialized // TODO - add your own initialization code here

2. Insert initialization code below the comment lines as shown in bold in the following code sample. Code Example 5: Session Bean Initialization Code // Perform application initialization that must complete // *after* managed components are initialized // TODO - add your own initialization code here // Keep the same locale across requests... sessionEncoding = new String("UTF-8"); // Description settings for initializing localeDropDown on Page1 dropDownOptionsDescriptions = new com.sun.rave.web.ui.model.Option[] { new Option("en_US", "English" ), new Option("ru_RU ", "Russian " ), new Option("ja_JP ", "Japanese " ), new Option("zh_CN ", "Chinese") };

3. To eliminate errors due to unresolved symbols in the file, right-click in the Java Editor and choose Fix Imports from the pop-up menu. If a dialog box opens because more than one package contains a class name, select the fully qualified name that contains com.sun.rave.web.ui.model.Option, then click OK. Your SessionBean.java file should now show no errors due to unresolved symbols.

Creating Properties Bundle


1. In the Projects window, expand the HelloBundledWorld > Source Packages > hellobundledworld node. Right-click the Bundle. properties node and choose Open from the pop-up menu. The Properties Editor opens. 2. Click New Property to open the New Property dialog box. Enter the following values, then click OK:
r r r

Key: hello Value: Hello, whole world! Comment: Greeting

3. Again, click New Property to open the New Property dialog box. Enter the following values, then click OK:
r r r

Key: enterSomeText Value: Enter some text: Comment: Text getter function

4. One last time, click New Property to open the New Property dialog box. Enter the following values, then click OK:
r r r

Key: youEntered Value: You entered: Comment: Text user entered

You should now see the keys and values you entered in the Properties Editor as shown in the following figure. These values will be used as default strings when the application replies to client browser requests.

Figure 8: Properties Editor Showing New Keys and Values

Adding Locales to the Properties Bundle You now add locales to the properties bundle and provide key values that can be used for other languages. 1. In the Projects window, right-click the HelloBundledWorld > Source Packages > hellobundledworld > Bundle.properties node and choose Add Locale from the pop-up menu. The New Locale dialog box opens. 2. In the New Locale dialog box, scroll down the Predefined Locales list and select the ru_RU - Russian/Russia locale as shown in the following figure. Click OK.

Figure 9: New Locale Dialog Box, Showing Russian Locale 3. Again, right-click Bundle.properties and choose Add Locale. In the New Locale dialog box, select the ja_JP - Japanese / Japan locale, and click OK. 4. Again, right-click Bundle.properties and choose Add Locale. In the New Locale dialog box, select the zh_CN - Chinese/ China locale, and click OK. The Properties Editor should now display the additional locales in new columns, as shown in the following figure.

Figure 10: Properties Editor Showing Added Locales

Supplying Language-Specific Values You now supply language-specific values for the keys in each locale. 1. In the Projects window, go to the HelloBundledWorld > Source Packages > hellobundledworld > Bundle.properties node and double-click the ja_JP - Japanese (Japan) node. The properties file opens in a text editor. 2. Edit the file to match the following code sample: Code Example 6: ASCII Code for Japanese (Japan) Text # Sample ResourceBundle properties file #Greeting hello=\u4E16\u754C\u3001\u4ECA\u65E5\u306F \! #Text getter function enterSomeText=\u5165\u529B\u3057\u3066\u4E0B\u3055\u3044\uFF1A\: #Text user entered youEntered=\u3042\u306A\u305F\u306F\u3053\u308C\u3092\u5165\u308C\u307E\u3057\u305F\:

The values you enter are character codes for the Japanese characters that will be displayed. Save the file and close the text editor. 3. Return to the Properties Editor and view the values in the Japanese column. If your system is able to display Japanese, your Properties Editor should look like the following figure.

Figure 11: Properties Editor Showing Japanese Characters Note that you can also enter international characters directly into the Properties Editor instead of entering their codes in the text editor. You can also copy and paste international characters into the value fields in the Properties Editor. 4. Enter Russian and Simplified Chinese characters either into the Properties editor or into the individual properties files with the text editor. The ASCII text in your properties files should look like code samples 7 and 8, and your Properties Editor should look like

Figure 12. NOTE: Due to space constraints, the enterSomeText line is wrapped across three lines in the sample Russian code below. In your file, be sure to include the enterSomeText information on a single line. Code Example 7: ASCII Code for Russian (Russia) Text #Greeting hello=\u0412\u0441\u0435\u043C \u043F\u0440\u0438\u0432\u0435\u0442 \!

#Text getter function enterSomeText=\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u043A\u0430\u043A\u043E\u0439-\u043B\u0438\u0431\u043E \u0442\u0435\u043A\u0441\u0442\: #Text user entered youEntered=\u0412\u044B \u0432\u0432\u0435\u043B\u0438\:

Code Example 8: ASCII Code for Simplified Chinese Text #Greeting hello=\u4E16\u754C, \u60A8\u597D\! \u4ECA\u65E5\! #Text getter function enterSomeText=\u8F93\u5165\: #Text user entered youEntered=\u4F60\u9009\u62E9\:

Figure 12: Properties Editor Showing Internationalized Text 5. Save and close the Properties Editor.

Adding a Tag in Page1.jsp You will now add a tag in the Page1.jsp file that directs the application to the resource bundle. 1. View Page1 in the Visual Designer. From the Advanced section of the Components Palette, drag a Load Bundle component onto an empty part of the page. The Load Bundle component creates the <f:loadBundle ...> directive in the Page1.jsp code. 2. In Outline window, ensure that Page1 > f:loadBundle:messages1 node is selected and view its properties in the Properties window, as shown in the following figure. Note that the value of var is messages1. You will use this value to bind Static Text and Label components in the user interface to strings in the properties bundle.

10

Figure 13: Viewing Properties for f:loadBundle:messages1 3. In the Outline window, select the page1 > html1 > body1 > form1 > gridLarge > helloText component, right-click, and choose Bind to Data from the pop-up menu. In the resulting dialog box, click Bind to an Object and enter #{Page1.helloText} as the Current Text property setting. Click OK. 4. With the helloText component selected in the Outline window, locate the text property in the Properties window. Enter the following value for the property: #{messages1.hello}. This value is a binding expression that will bind the displayed text for the component to the value of the hello key at run time. 5. In the Outline window, select the enterTextLabel component. In the Properties window, enter the following value for the text property: #{messages1.enterSomeText}. 6. In the Outline window, select the youEnteredLabel component. In the Properties window, enter the following value for the text property: #{messages1.youEntered}. 7. In the Outline window, select the youEnteredDisplay component, right-click, and choose Property Bindings from the pop-up menu. In the Property Bindings dialog box, select the text property and the binding target Page1 > capturedText, as shown in the following figure. Click Apply, then Close.

Figure 14: Binding the text Property for the youEnteredDisplay Component 8. In the Outline window, select the textEntry component, right-click, and choose Property Bindings from the pop-up menu. In the Property Bindings dialog box, again select the text property and the Page1 > capturedText target. Click Apply, then Close. 9. In the Outline window, select the page1 > html1 > body1 > form1 > gridLarge > gridUpperRight > localeDropDown component, right-click, and choose Property Bindings from the contextual menu. In the Property Bindings dialog box, select the items property and the SessionBean1 > dropDownOptionsDescriptions target. Click Apply, then Close.

11

Editing the faces-config.xml File You now edit the faces-config.xml file to configure the supported locales for your application. 1. Open the Files window, expand the HelloBundledWorld > web > WEB-INF node and right-click the faces-config.xml node. Choose Edit from the pop-up menu, and the file opens for editing. 2. Edit the <faces-config> tag to match the following code sample. Make sure you have removed the comment lines that are present in the default file around the <application> tag. Code Example 9: Specifying Default and Supported Locales in faces-config.xml <faces-config> <application> <locale-config> <default-locale>en</default-locale> <supported-locale>ru</supported-locale> <supported-locale>ja</supported-locale> <supported-locale>zh</supported-locale> </locale-config> </application> </faces-config>

Note that the <supported-locale> tags above specify only the language codes (for example, ja) and do not include the locale codes (for example, ja_JP). Not all browsers can accept locale codes, so they have been omitted. 3. Save the file and close the editor.

Testing Your Application


Build and run the application by choosing Run > Run Main Project. If all goes well, your browser will open to show the English version of the application. By choosing different languages from the drop-down list, you will see the values you entered in the bundled properties files substituted in the user interface. When you enter text in the text field (the text was copied and pasted in the following figure), it will be echoed in the Static Text component below the Text Field.

12

Figure 15: Application at Run Time Displaying International Text

Summary
In this tutorial, you first set up your system and browser to display English, Russian, Japanese, and Simplified Chinese characters, in UTF8, Shift_JIS, and GB2312 encodings. You then laid out a page using Basic components. You created a resource bundle, entering values that were strings in the four languages. You then bound the display properties of the components to keys in the resource bundle. At run time, the user was able to select one of the languages from a drop-down list. The selection caused the client browser to request the application server to compose a page in the chosen language. By referring to the values in the bundled properties files, the server composed and served a page in the requested language and encoding. Making use of a bundled resource of properties, the sample application responds to user choice of one of four locales and characters encodings. After the user chooses a locale and encoding, the application server sends text for display in that encoding and accepts text entered by the user in the same encoding. Giving users the ability to specify a locale and encoding lets your application accommodate the broadest possible number of users, including those with legacy encodings or other unusual needs. See Also:
q

Understanding Internationalization

13

More Developer Resources: For more tutorials, articles, tips, forums, updates, and expert advice for developers, visit the Java Studio Creator developer resources on the Sun Developer Network (SDN) at http://developers.sun.com/jscreator/.

This page was last modified: June 23, 2006

Sun and Third-party Trademarked Terminology


The following Sun trademarked terms might be used in the Sun Java(tm) Studio Creator tutorials:
q q q q q q q q q

Sun Java Studio Creator integrated development environment (IDE) Sun Java System Application Server version number (Application Server) Java Platform, Standard Edition technology (Java SE(tm) platform) JavaServer(tm) Faces technology JavaServer Pages(tm) technology (JSP(tm) technology) Sun Java System Web Server version number (Web Server) Java Database Connectivity software (JDBC software) Enterprise JavaBeans(tm) specification (EJB(tm) specification) Solaris(tm) Operating System software (Solaris OS software)

The following third-party trademarked terms might be used in the Sun Java Studio Creator tutorials:
q q

UNIX(R) software SPARC(R) processor

Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved. Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. In particular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed at http://www.sun.com/ patents and one or more additional patents or pending patent applications in the U.S. and in other countries. U.S. Government Rights - Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions of the FAR and its supplements. Use is subject to license terms. Sun, Sun Microsystems, the Sun logo, Java and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.This product is covered and controlled by U.S. Export Control laws and may be subject to the export or import laws in other countries. Nuclear, missile, chemical biological weapons or nuclear maritime end uses or end users, whether direct or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or to entities identified on U.S. export exclusion lists, including, but not limited to, the denied persons and specially designated nationals lists is strictly prohibited. Note: Sun is not responsible for the availability of third-party web sites mentioned in this document and does not endorse and is not responsible or liable for any content, advertising, products, or other materials on or available from such sites or resources. Sun will not be responsible or liable for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods, or services available on or through any such sites or resources.

Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, tats-Unis. Tous droits rservs. Sun Microsystems, Inc. dtient les droits de proprit intellectuels relatifs la technologie incorpore dans le produit qui est dcrit dans ce document. En particulier, et ce sans limitation, ces droits de proprit intellectuelle peuvent inclure un ou plus des brevets amricains lists l'adresse http://www.sun.com/patents et un ou les brevets supplmentaires ou les applications de brevet en attente aux tats-Unis et dans les autres pays. L'utilisation est soumise aux termes de la Licence. Sun, Sun Microsystems, le logo Sun, Java et le logo Java Coffee Cup sont des marques de fabrique ou des marques dposes de Sun Microsystems, Inc. aux tats-Unis et dans d'autres pays.Ce produit est soumis la lgislation amricaine en matire de contrle des exportations et peut tre soumis la rglementation en vigueur dans d'autres pays dans le domaine des exportations et importations. Les utilisations, ou utilisateurs finaux, pour des armes nuclaires,des missiles, des armes biologiques et chimiques ou du nuclaire maritime, directement ou indirectement, sont strictement interdites. Les exportations ou rexportations vers les pays sous embargo amricain, ou vers des entits figurant sur les listes d'exclusion d'exportation amricaines, y compris, mais de manire non exhaustive, la liste de personnes qui font objet d'un ordre de ne pas participer, d'une faon directe ou indirecte, aux exportations des produits ou des services qui sont rgis par la lgislation amricaine en matire de contrle des exportations et la liste de ressortissants spcifiquement dsigns, sont rigoureusement interdites.

14

Sun Microsystems n'est pas responsable de la disponibilit de tiers emplacements d'enchanement mentionns dans ce document et n'approuve pas et n'est pas responsable ou iresponsable d'aucun contenu, de la publicit, de produits, ou d'autres matriaux dessus ou fournis par de tels emplacements ou ressources. Sun ne sera pas responsable ou iresponsable d'aucuns dommages ou perte causs ou allgus pour tre caus par ou en liaison avec l'utilisation de ce produit ou la confiance dans des tels contenu, marchandises, ou services disponibles sur ou par des tels emplacements ou ressources.

15

You might also like