internationalizing apps

Upload: nyellutla

Post on 14-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 InternationaliZing Apps

    1/19

    Understanding Internationalization

    May 2006[Revision number: V2.1-1]Copyright 2006 Sun Microsystems, Inc.

    This tutorial provides background information to help you develop an internationalized web application with the Sun Java StudioCreator application development tool, using JavaServer Faces components. It provides an example of localizing an application for aspecific locale.The Sun Java Studio Creator IDE enables you to develop localized web applications specific to a single locale or supporting manylocales. The easiest way to develop an application for a single locale is to have the IDE inherit its default settings from the localesettings of your operating system.The IDE also lets you develop internationalized web applications that can be automatically localized to many different locales. Therecommended way to do so is to use a properties bundle that segregates your human-readable text into one set of files for easymaintenance.

    Contents

    - What Is Internationalization

    - Locale, Character Sets, and Encoding- Unicode and UTF-8

    - Locale Settings and Character Encodings in the IDE

    - Localized Project Development

    - Internationalization Features in the IDE

    - Source Encoding Settings

    - Supported Locales

    - Encoding Component

    - Default Locale and Response Encoding

    - UrlLang Property

    - Lang Property

    - Language Property

    - The Charset Property

    - The Hreflang Property

    - The Dir Property- Bundled Properties

    - Load Bundle Component

    -Internationalization Properties in JavaServer FacesFiles

    - The faces-config.xml File

    - Example

    Example used in this tutorial

    internationalizingapps_ex.zip (zip)

    What Is Internationalization

    Internationalization is the process of making program code generic and flexible so that it can easily accommodate specificationsfrom markets around the world. These specifications includebut are not limited tolanguage, character sets, date and timeformats, and currency symbols. Readers familiar with issues involving internationalization, localization, and character encoding maywish to skip directly to the topic Localized Project Development.

    Internationalization enables localization, the ability to develop a user interface for a specific locale (a geographic, political, orcultural region). It is usually identified by the two-letter ISO-639-2 language code and the two-letter ISO-3166 country code for thelocale. For example, en_USrepresents the locale United States English. In some cases, only a language identifier is provided.

    1

    http://www.loc.gov/standards/iso639-2/englangn.htmlhttp://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/index.htmlhttp://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/index.htmlhttp://www.loc.gov/standards/iso639-2/englangn.html
  • 7/30/2019 InternationaliZing Apps

    2/19

    The Sun Java Studio Creator application development tool (the IDE) enables you to create localized versions of your program,where each localized version supports a target locale. It generates internationalized code, so that your program can behave as alocalized application in different locales.

    Locale, Character Sets, and Encoding

    Character encoding issues are not exclusive to internationalization; they affect any developer whose application will run in aspecified locale even if the application doesn't display messages specific to that locale. However, it is difficult to understand theprocess of internationalization without understanding character encoding.As already mentioned, a locale is usually identified by a two-letter language code and a two-letter country code. Each language (andin some cases, each locale) may require a different character set. The character set is the set of glyphs (the alphabet, numbers, andpunctuation) used in the language. Character sets are comparatively small for European languages, numbering in the hundreds ofglyphs. For other locales, especially those in Asia, character sets can number in the tens of thousands of glyphs.Character encoding is the mapping of code points, represented as integers, to the glyphs in a character set. The mapping between acode point and a symbol is typically set by a standards committee such as the International Standards Organization (ISO). Encodingscan also be defined by manufacturers who want to define special glyphs of their own. Locales with large character sets require codepoints of at least two bytes (16 bits) to represent all of the glyphs, but variable byte-length encoding schemes have been designed touse as many as 6 bytes for some glyphs.

    Any single language can have more than one encoding. And, although two different character encodings may provide the same set ofcharacters, their code points refer to different glyphs. To add to the confusion, there can be several names for the same encoding. Toread more on encoding, you can go to several sources, starting with the ISO web site.

    Unicode and UTF-8

    Unicode is the international standard whose goal is to specify a code that maps every character needed by every written humanlanguage to a single unique integer code point. Despite difficulties, Unicode has emerged as the dominant encoding scheme inmultilingual environments.The Java Studio Creator IDE defaults to the UTF-8 encoding (8-bit Unicode Transformation Format) as the most flexibleimplementation of the Unicode standard. It is a lossless, variable-length character encoding that uses groups of bytes to represent the

    Unicode standard for the alphabets of many of the world's languages. It is the default encoding for the XML format.UTF-8 uses 1 to 4 bytes per character, depending on the Unicode symbol. For example, only one UTF-8 byte is needed to encode the128 US-ASCII characters. An ASCII file encoded in UTF-8 is exactly the same as the original ASCII file. All non-ASCII charactersin the encoding are guaranteed to have the most significant bit set, whereas ASCII characters do not. This means that existing toolsused with ASCII text (searching, text editing, and so on) work as expected, and that legacy systems such as emailers can transmitUTF-8.UTF-8 guarantees that no byte sequence of one character is contained within a longer byte sequence of another character. Thisensures that byte-wise sub-string matching can be applied to search for words or phrases within a text. Most other variable-length 8-bit encodings do not have this property, making string matching difficult.

    Locale Settings and Character Encodings in the IDE

    The Java Studio Creator IDE gives you control of locale and character encoding in several ways. As the preceding discussion pointsout, locale and character encoding are separate settings. However, you will usually find an association between the two settingsbecause of font availability.

    NOTE: A typeface is a design of a set of letters, numbers, and special symbols that share a particular appearance, such as theHelvetica or Times Roman typefaces. Afontis an implementation of a typefaces character set. At one time, fonts were expressed inhardware. However, modern fontsoften dynamically generatedare available as software associated with an operating system.

    As a developer, you must consciously target the platforms and character encodings that will support your application. For web

    2

    http://www.iso.org/iso/en/ISOOnline.frontpagehttp://www.iso.org/iso/en/ISOOnline.frontpage
  • 7/30/2019 InternationaliZing Apps

    3/19

    applications, the target platform for your development effort is not a computer or even an operating system, but a web browser.Popular browsers, in turn, are implemented for several operating systems. Because fonts are distributed with operating systems,popular browsers must accommodate each system's available character encodings. A modern browser can handle many different fontencodings.

    In the Java Studio Creator IDE, you will typically select a specific character encoding, such as Shift_JIS encoding whenever youspecify the locale ja_JP, or Big5 encoding whenever you specify a traditional Chinese locale such as zh_TW.

    Browsers provide preference settings to inform internationalized sites of the user's preferred language. The web server receiving thisinformation attempts to serve pages in the preferred language of the client browser.

    The ability to specify character encodings as well as locales is important because not all encodings for a specific language are thesame. For example, consider Figure 1, which shows a sample of Chinese text displayed in three different encodings on the samebrowser. The encoding in each case is the response encoding, the encoding specified by the web server when it composes a page andsends it to the client browser. When the browser receives a page specified in, for example, UTF-8 encoding, it attempts to render thepage using its UTF-8 fonts.

    Figure 1: Rendering Differences in Chinese Character EncodingsThe circled characters in Figure 1 show that UTF-8, Big5, and GB2312 can have significant differences when displayed on the samebrowser. GB2312 encoding is typically used in mainland China; Big5 in Taiwan.

    One character code at the bottom the Big5 encoding sample is not rendered as a Chinese glyph at all, indicating that the passage wasprobably intended for GB2312 (simplified Chinese) encoding. Fonts used for UTF-8 encoding are similar to those used for Big5 inthis sample, although different punctuation spacings produce different line breaks.To further complicate the situation, different browsers may behave differently. For this reason, some web applications, especiallythose adapted for Chinese, give the user a choice of encodings.

    3

  • 7/30/2019 InternationaliZing Apps

    4/19

    Localized Project Development

    The Java Studio Creator IDE enables you to develop web-based applications in many languages. To successfully deploy and testwhile developing a web-based application in a specific language, you must start up the IDE on a development computer with thesame character encoding as the target computer where you plan to run the server.

    The browser must also support the target language. As you develop your application, all JavaServer Pages (JSP) files and Javasource files may be maintained in the native encoding of your operating system, as is true of many other popular IDEs. This featureallows the IDE to work interchangeably with other tools. Alternatively, you may choose to store all JSP and Java source files in UTF-8 encoding. The use of UTF-8 circumvents encoding problems if you need to share your files in an internationally distributeddevelopment team. In such cases, you can maintain a central source code repository because the operating system encodings used towrite files will not differ among locales.

    Additionally, you can work with multiple languages in a single JSP page by setting up the environment to use UTF-8 encoding.However, this option is only available on platforms that support UTF-8 fonts.

    Only one completely reliable way exists to change the default encoding that is used by the virtual machine and the runtime system.You must change the locale of the underlying operating system before you start the IDE. For example, on Windows XP Professional,you set the locale from the Regional and Language Options control panel.

    If you change the encoding or locale of your project midstream, the text or language directives in your project JSP and Java files

    may lose synchronization. As a result, your application could become corrupted. To recover, go back through the project and ensurethat all Java files are of the same source encoding and that all existing JSP tags correctly coincide with the project default languageand locale encoding settings. See the section Changing Source Encoding In Existing Projects for more information.

    Internationalization Features in the IDE

    To create an internationalized application, you must manage locale and character encoding parameters. The IDE lets you managecharacter encodings and locales, primarily through a set of encoding properties and options.

    Although standardizing on a single encoding such as UTF-8 is highly desirable because of its acceptance by ASCII-centricprograms, the present state of technology requires compromise because some existing platforms cannot handle UTF-8, or there issome compelling cultural or legacy requirement. In general, UTF-8 encoding is recommended for all language encodings exceptSimplified Chinese, where other encodings such as GB2312 predominate. Therefore, you may need to change the default behavior.

    The remainder of this tutorial explains the features, properties, and options of the IDE that affect localization andinternationalization.

    Source Encoding Settings

    Source Encoding settings determine the character encoding for source files (.jsp and .java files) in your project. The settingsproduce headers and tags in the source files that allow the readers of the files to interpret them correctly.

    Default Source Encoding Option

    The Default Encoding option sets the default encoding for new project source files. If you do not enter a value for the option, theIDE uses a source encoding based on the current locale and encoding settings for your computer. The value of the option can be

    overridden by properties in individual source files.To change the default source encoding, choose Tools > Options from the menu bar and click the Advanced radio button (see Figure2). Select the Java Sources option and, if necessary, expand the Expert category to reveal the Default Encoding option.

    If the value of the option is blank, the IDE uses the default system encoding. To change the encoding, click in the value field to theright of the Default Encoding property and enter the encoding of your choice. Alternatively, click the button next to the value fieldand enter an encoding in the resulting dialog box.

    4

  • 7/30/2019 InternationaliZing Apps

    5/19

    Figure 2: Java Sources Default Encoding OptionIndividual Java Source File Encoding

    When you edit a Java source file in the Java Editor or select its name in the Projects or Files window, the Properties window displaysthe file's Text > Encoding property (see Figure 3). This is the source encoding of the individual Java file. If there is no entry for thisproperty, the IDE uses the Default Encoding option for the page.

    To change the Encoding property, click the button to the right of the property and enter a different encoding, such as UTF-8 orShift_JIS.

    Figure 3: Page Text Source EncodingProperty

    If you need to change the source encoding property for a file, the new encoding does not take effect until the project has been saved.If you discard your changes, the property will persist in the Properties window, but the file will not have been saved in the newencoding. You must save your file with the new encoding for it to have the new encoding next time you work with it. If your file hasnot been changed, make a small edit so you can save the file. For example, add and then delete a character so that you can save yourfile.

    If you change the encoding for a Java source file, you must change other existing Java files to match. All Java files are passed to the

    compiler at the same time, and the compiler can only accept one encoding flag. Therefore, all Java source files must be in the sameencoding for each build. To synchronize the settings in your source files, touch each of them (add and delete a character) and savethe project.

    If your Java source contains hard-coded strings, they will be changed when you change the encoding for the source file and save it.So, for example, if you begin with UTF-8 encoding and you change the encoding to Shift_JIS, the IDE will convert the file whenyou save it in the new encoding. The hard-coded strings will appear correctly in the new encoding when displayed to the user.

    5

  • 7/30/2019 InternationaliZing Apps

    6/19

    The Default Encoding property for the project determines the encoding of new source files. However, if you change this property ina project midstream, existing source files retain their original encodings. The text encodings of Java files should be changed tomatch the new Default Encoding property.

    Likewise, if you change the encoding of your existing Java files, you should change the default source encoding property to matchso that new files will be synchronized.

    To change the source encoding for an existing project:

    1. Change the project Default Encoding option (as described in Default Source Encoding Option).

    You now need to change the source encoding for the Java source files already in the project.

    2. Select a Java source file in the Files window, as shown in the following figure.

    Figure 4: Selecting a Source File in the FilesWindow

    3. View the properties for the file in the Properties window. If the Text > Encoding property is not blank, select and delete the

    entry to apply the default value, or enter a different encoding. Alternatively, click the button next to the property and edit the

    value in the dialog box.

    If the IDE prevents you from editing the value, edit and save the file as described in the next two steps, then try again.

    4. Double-click the file node in the Files window to open the file in the Java Editor.

    5. Enter and delete a character in the file and select File > Save to save the file.

    6. Repeat steps 2 through 5 for each Java source file in the project.

    Supported Locales

    The locales supported by your application can be set in the faces-config.xml file. You can view or edit this file by viewing the

    project's Files window, then expanding theproject_name > web > WEB-INF node. For more information, see The faces-config.xml File.

    Also, for your application to display correctly in the desired locales, you can add localized strings to the project's resource bundle.The resource bundle stores selected characteristics of each locale as key-value pairs in properties files, typically one file for eachlocale. The properties files are used to store localized strings.

    The properties files can be seen when a page is displayed in the Visual Designer. In the Files window, view the files by expandingtheproject_name > src >project_name > bundle.properties node. In the Projects window, view the files by expanding theproject_name > Source Packages >project_name > bundle.properties node. Bundled property files are explained in the

    Changing Source Encoding in Existing Projects

    section Bundled Properties.

    6

  • 7/30/2019 InternationaliZing Apps

    7/19

    Encoding Component

    The Encoding component is used to set dynamically the locale for a page in your application. It is available from Palette > Advanced> Encoding. By default, the Encoding component obtains the encoding from your application bean. To see how it works:

    1. View a page in the Visual Designer.

    2. In the Palette window, click the Components tab.

    3. Expand the Advanced category and drag an Encoding component onto a page in the Visual Designer.

    4. In the Outline window, an instance of the component will appear in the page > html > head > node (see Figure 5). When youselect the encoding component node, the Properties window shows that its value is bound to the application beanslocaleCharacterEncoding property in this case, #{ApplicationBean1.localeCharacterEncoding}.

    Figure 5: Viewing Properties for the Encoding Component

    5. In the Outline window, double-click the application bean node (ApplicationBean1) to open the Java source file for the bean inthe Java Editor.

    6. Near the bottom of the file, locate thegetLocaleCharacterEncoding()method. This method returns a characterencoding based on the Locale defined for the current JavaServer Faces view.

    The default behavior of this method in the standard ApplicationBean1 class is as follows: If the locale for this request isSimplified Chinese (zh_CN), return GB2312. Otherwise, return UTF-8.

    You can change the default behavior by editing the getLocaleCharacterEncoding()method to return a differentlocale. For example, if the locale is found to be RU_ru, you could return the encoding KOI8-R instead of UTF-8.

    Default Locale and Response Encoding

    You will now explore how your web application responds to client browser requests for a specific locale.

    If a browser requests a locale that your application can support, your web application will respond with pages generated for therequested locale. If your web application does not support the requested locale, it will respond by generating a web page for thelocale specified by the localeCharacterEncoding property of your application bean.

    For example, if the user's web browser requested the Russian locale, the application would use the bundle_ru_RU.properties file instead of the default bundle.properties file to build that user's web page. Bundled property files areexplained in the section Bundled Properties.

    The Response Encoding property is the default character encoding that the application server uses when it responds to abrowser request. Its value is a code that specifies the character encoding used in the page. Character encoding is expressed as the

    7

  • 7/30/2019 InternationaliZing Apps

    8/19

    charset parameter of the HTTP Content-Type tag in the submitted page header. If the browser requests a different locale, aresponse encoding for that locale is used instead, if possible.

    When a client browser requests a page from your web application, the default response of the application is as follows:

    q The application opens a JSP file, converts the file into internal Java Unicode, using the tag to determine the files encoding, and brings it into memory.

    q Following the directives in the JSP file and the HTML style sheet, the application generates the required servlet and HTMLin the encoding specified in the tag

    q The application assembles the complete page, encodes it in the specified encoding, and delivers it to the client browserthrough the web server.

    The client browser can attempt to override the default response encoding by asking for a specific language in its request Russian,for example. The web application may accept that request, note that Russian is available in the web application in UTF-8 encoding,and deliver the page in UTF-8 encoding with string elements from the Russian resource bundles.Alternatively, you could have decided to specify your application's Russian response encoding as KOI8-R, an encoding still popularin Russia. In this case, your application converts the JSP file into Unicode in memory, then converts that intermediate representationinto KOI8-R and delivers the page. The client browser displays the page in Russian and accepts user input as KOI8-R encoding.When the user submits the page,the client browser includes a header notifying the web server that the page is encoded in KOI8-R,enabling the server to interpret the request.

    Each request and response is associated with an encoding. If a client browser does not send an encoding specification, theapplication server assumes that the request is in the same encoding as the response it sent most recently.

    Changing Response Encoding of a Page

    You can change the response encoding for individual JSP files in the IDE project.

    1. In the IDE's Visual Designer, click the background of the page and view the properties for the page. The Properties windowwill show the Advanced > Response Encoding property, similar to the following figure.

    Figure 6: Viewing Response EncodingProperty

    2. If the ResponseEncoding property is not blank, select and delete the entry to apply the default value, or enter a different

    encoding. Alternatively, click the button next to the property and edit the value in the dialog box.

    3. View the source file for the page by clicking the JSP tab.

    4. Enter and delete a character in the file so that it can be saved, and select File > Save to save the file.

    UrlLang Property

    The urlLang property applies to the link components Hyperlink and Image Hyperlink. It specifies the language used in theresource referred to by the url property of these components. In the rendered page, the property is expressed as the hreflangattribute of the HTML tag.

    8

  • 7/30/2019 InternationaliZing Apps

    9/19

    1. Drag a Hyperlink or Image Hyperlink component from the JSF Palette onto the Visual Editor.

    2. Select the component (not the hyperlink text inside it).

    NOTE: If you have selected the text, you can expand it to the component by pressing the Esc key or clicking the component

    a second time. Alternatively, you can select the component in the Application Outline, as shown in the following figure.

    Figure 7: Viewing Properties for a Hyperlink Component

    3. View the Advanced properties on the Properties window. You will see theurlLang property.

    4. To edit a language code, click the ellipsis button (...) to open the Property Editor, in which you can change the value of theproperty. The following figure shows the Properties Editor for the urlLang property. A value ofru has been entered so thatonly language codes containing these consecutive characters are displayed.

    Figure 8: Properties Editor for urlLang Property, Use ValueYou can either define the language code directly on the Use Value panel shown in the preceding figure or use the UseBinding panel to bind the property to a bean property (either data provider or object) and enable your application to set thelanguage code dynamically.

    The IDE uses the same editor interface for the urlLang and lang properties (lang is discussed below). The followingfigure shows lang being bound to a pattern in a projects session bean. Binding to a property of the session bean is usefulwhen you want to bind the component property to a property of the session bean in which you maintain the language codesfor your application.

    9

  • 7/30/2019 InternationaliZing Apps

    10/19

    Figure 9: Properties Editor for lang Property, Use Binding

    Lang Property

    The lang property specifies the language used in the generated markup for a Grid Panel component. The property is visible in theProperties window when you select a Grid Panel component in the Visual Designer.

    The lang property is expressed as the HTML lang attribute in the tag. This attribute specifies the character encodingof the resource designated by the link. It is intended to allow user agents to render content meaningfully based on accepted culturalpractice for a given language. It can be used to declare the language of a web page or a portion of a web page. Clicking the buttonnext to the property brings up the same Properties Editor shown in Figures 8 and 9.

    Language Property

    A Language property is associated with each JSP page of your application. The property specifies the language used in thegenerated markup for the page. It is expressed as the lang attribute of the HTML tag. To change the property value,display a page in the Visual Designer and view its properties in the Properties window. Click the ellipsis button (...) next to theAdvanced > Language property.

    If a component on the page has a lang property setting different from this setting, then the value of the lang property is used forthat component.

    The Charset Property

    The charset property is associated with the url property of link components such as Hyperlinks, and specifies the characterencoding of the document or resource that is the target of the link. It is expressed as the charset attribute of the the HTML tag when the page is rendered. For a list of encodings, refer to http://www.iana.org/assignments/character-sets.

    Strictly speaking, character sets are not encodings; however, the HTML specification has given the encoding attribute the charsetname.

    10

    http://www.iana.org/assignments/character-setshttp://www.iana.org/assignments/character-sets
  • 7/30/2019 InternationaliZing Apps

    11/19

    To view the property:

    1. View a page in the Visual Designer.

    2. If there is no Link component on the page, drag a Link component onto the page in Design view.

    3. In the Outline window, select the page > html > head > link1 node as shown in the following figure and view the Linkcomponents properties in the Properties window.

    Figure 10: Selecting a Link ComponentInstance in the Outline Window

    To change the charset property:

    1. Click the ellipsis button next to the charset property in the Properties window.

    2. A dialog box opens in which you can choose an encoding. The dialog box is similar to the one shown in Figures 8 and 9. Inthe Use Value pane, use the Filter field to enter a character string that narrows your view of available character sets.

    The encoding you specify provides a hint of the encoding of the target. This hint helps the browser to link appropriately.The list in the dialog box shown in Figure 8 is the published list of all character encodings in official use, as defined by the W3C.However, the list may be incomplete in that it may not have all known aliases of each encoding.

    Adding a New EncodingBecause some proprietary encodings may exist that are not available from the list, you can add one by clicking the New button in thedialog box. Proprietary encodings are sometimes developed by organizations that wish to display special characters not availableelsewhere. Such sites generally must prompt the user to download a proprietary font package and encoding before the site can beviewed.

    The Hreflang Property

    The hreflang property applies to Standard link components. It is used and edited just as the urlLang property is for Basic andAdvanced link components. New projects should avoid using Standard components.

    The Dir Property

    The dir property applies to layout components that may contain text display or entry components. To view the property, select aGrid Panel component in the Visual Designer and look in the Advanced category.

    The dir property is used to indicate the directionality of text and is useful when text does not inherit the correct directionality (forexample, because the text is English but the primary language for the page is Hebrew). The property is expressed as the dir

    11

  • 7/30/2019 InternationaliZing Apps

    12/19

    attribute of the HTML tag in the rendered page. Strictly speaking, this attribute is not part of language encoding.However, it controls how alphabets are displayed.

    The property's values can be one of the following:

    LTR (Left-to-right)RTL (Right-to-left)

    Bundled Properties

    An application can be localized by specifying a single locale and encoding, or simply by setting your operating system to the localeand encoding of the target platform before you open the IDE. However, to internationalize a project, the best practice is to segregateall user-visible strings into bundled properties files so that they can be easily translated for various locales.

    When you create a new project, the IDE creates a Bundle.properties file that serves as the default language and locale foryour project. The default is based on your computers system settings for language and locale. You can then add properties to the filein the form of pairs of key-value strings, with values expressed in the language of the locale. When you add a locale to the bundle,you create a new properties file specific to that locale. The properties file for each locale you add contains the same keys, but thevalues are specific to the locale.

    When a client browser specifies one of the locales, the application can compose a page in the requested locale using elements fromthat locale's resource bundle and the encoding you have specified elsewhere in your properties settings.

    To add a locale to your project, right-click the bundle.properties node in the Files or Projects window and choose AddLocale, as shown in the following figure.

    Figure 11: Adding a LocaleA New Locale window opens in which you can enter language, country, and variant codes, select them individually from drop-downlists, or choose combinations from a list of predefined locales, as shown in the following figure.

    12

  • 7/30/2019 InternationaliZing Apps

    13/19

    Figure 12: Specifying a New Locale

    To edit a properties file, you can double-click its node in the Files or Projects window. The Java Editor will open, and you can enterkey-value pairs in the form ofkey=value, as shown in the following figure.

    Figure 13: Editing a .properties File in Java EditorTo edit the bundle in a Properties Editor:

    1. Right-click on thebundle.properties node in the Files or Projects window.

    2. Choose Open from the contextual menu, as shown in the following figure.

    13

  • 7/30/2019 InternationaliZing Apps

    14/19

    Figure 14: Opening a Properties Bundle

    The Properties Editor opens, as shown in the following figure.

    Figure 15: Editing a Properties Bundle

    3. Edits you make to Key values in the first column will be applied to all bundled properties files. You can edit the keys orvalues directly in the table or in the text entry fields below the table. Comment fields are provided to help you remember theuse of each key-value pair.

    4. Clicking the New Property button opens a dialog box in which you can enter a new key, value, and comment. Your entriesare applied to all the files in the bundle. You can then edit the values for the new property in each locale.

    5. To remove the current property, click the Remove Property button.

    Your project accesses the bundled properties files through a tag that is added to a page's JSP file when you

    14

  • 7/30/2019 InternationaliZing Apps

    15/19

    drop a Load Bundle component onto the page in the Visual designer (see below). When you deploy your application, the propertiesfiles are copied to the WEB-INF/classes/projectname directory for you, so that it is available for the tag to load.

    When your web application receives a request from a client browser to compose a page, it checks for a locale request. Theapplication then searches for the properties file that matches the locale, substitutes the values in the file for the keys wherever theyappear in your project, and composes the page in the proper encoding.

    Load Bundle Component

    The Load Bundle component is available from the Palette under the Advanced category. When you drag it onto a page in the VisualDesigner, it creates a custom tag in the JavaServer Pages code for a page. The tag exposes a resource bundle asa Map and lets you use the locales you have added to the resource bundle. The Load Bundle component is best understood byreferring to the example at the end of this tutorial.

    Internationalization Properties in JavaServer Faces Files

    When you view the JSP source for a page (by clicking the JSP tab in the Visual Designer), you see the effects of some of theinternationalization features. Three lines near the beginning of a JSP file reflect the property values for source encoding, responseencoding, and default locale. The following lines result from a source encoding of UTF-8, a default locale of ja-JP, and a responseencoding of Shift_JIS.

    Code Sample 1: Page Encoding

    ...

    ...

    Your system might display different default encoding aliases, depending on your operating system and locale. For example, youmight see MacRoman, MS950, or SJIS. Your native encoding name will be translated to a valid Internet Assigned NumbersAuthority (IANA) encoding to be used by the IDE when it encodes the JavaServer pages (JSPs) for your project.

    Note that the value of the following properties should be the same in your JSP files:

    q xml version=1.0 encoding, as shown in the code example aboveq pageEncoding, as shown in the code exampleq The Source Encoding property and the text encoding of the individual Java source files (discussed previously in the section

    Default Source Encoding Option)

    For localized applications, the value of the following properties should be the same. For internationalized applications, these values

    may be overridden at run time.

    q contentType=text/html;charset, as shown in the code exampleq Response Encoding property (discussed in the section entitled Default Locale and Response Encoding)

    15

    http://www.iana.org/http://www.iana.org/
  • 7/30/2019 InternationaliZing Apps

    16/19

    The faces-config.xml file, visible in the Files window beneath your project's web > WEB-INF node, is used to set the defaultand supported locales for your project, as illustrated in the following example.

    Example

    This simple example shows you how to localize an application for the Japanese locale. To complete this tutorial, you mustunderstand how to set up your development system and web browser for the Japanese language and locale.

    Setting Up a Localized System

    Before creating your project, you must set up your development system for the target language and locale. The IDE inherits thelanguage and locale settings of your system. (The specifics of how to do this for each operating system are beyond the scope of thistutorial. Consult the documentation for your system to enable the named locale.)

    This tutorial uses ja_JP, the Japanese language and locale.

    You must also set up your web browser to display Japanese characters. Consult the documentation for your browser for details.

    Creating a Localized Project

    1. Open the Java Studio Creator IDE. From the Welcome page, click Create New Project. Name the projectHelloWideWorld

    2. In the Visual Designer, drag a Static Text component from the Palette onto Page1.

    3. In the Files window, expand the project'sWeb > WEB-INF node and double-click the faces-config.xml file. The filewill open for editing.

    4. Remove the comments from the tag. Edit the tag to make Japanese the default locale and English asupported locale. Your code should look like the following code sample:

    Code Sample 2: Edited Tag in faces-config.xml File

    ja

    en

    5. Save the faces-config.xml file.

    6. In the File window, expand the HelloWideWorld > src > hellowideworld node and right-click the Bundle.properties node. Choose Open from the contextual menu. The Properties Editor opens.

    7. In the Properties Editor, click New Property. In the resulting New Properties dialog box, enter hello for key, helloworld for value, and Greeting for comment, as shown in the following figure.

    The faces-config.xml File

    16

  • 7/30/2019 InternationaliZing Apps

    17/19

    Figure 16: New Property Dialog Box

    8. In the Files Window, right-click the HelloWideWorld > src > hellowideworld > Bundle.propertiesnode and choose Add Locale from the contextual menu. The Add Locale dialog box opens.

    9. In the New Locale dialog box, enter the Language Code en and Country Code US, as shown in the following figure.

    Figure 17: New Locale Dialog Box

    10. In the Files window, double-click theHelloWideWorld > src > hellowideworld > Bundle.properties> default language node. The default language properties bundle file opens in a text editor.

    11. Enter character codes for Japanese greeting. The characters are the value of the hello key. The contents of the file shouldlook like the following code sample:

    Code Sample 3: Edited Default Language File

    #Greeting

    hello=\u3053\u3093\u306B\u3061\u306F\u4E16\u754C

    12. Save the file and close the text editor.

    13. Click the Properties Editor tab. The value of the hello key in the default language column should be shown in Japanesecharacters. Note that you can edit these characters directly in the Properties Editor as Japanese text, either from the keyboardor by copying and pasting from another application. In this example, you entered the Japanese characters as ASCII code inthe text editor instead.

    14. Close the Properties Editor.

    15. View Page1 in the Visual Designer. From the Components Palette, drag the Advanced > Load Bundle component onto thepage background. This component creates a tag in the JavaServer Pages code for the file.

    16. Click the JSP tab in the Visual Designer and locate the tag. It should read as follows:

    17

  • 7/30/2019 InternationaliZing Apps

    18/19

    You will use the value ofvar to bind the text of the Static Text component to the value of the hello key in the resourcebundle.

    17. View Page1 in the Visual Designer and select the Static Text component. View its properties in the Properties window.

    18. In the Properties window, click the ellipsis button next to the text property. Enter the value #{messages1.hello} andclick OK. Note that the Static Text component no longer shows text in the Visual Designer. At run time, it will showJapanese text if the browser is enabled to display it. Otherwise, it will display English text.

    Testing Your Example Application

    Click the Run arrow at the top of the IDE window to deploy and run your project. If all goes well, your browser will open withPage1 and the Japanese characters will be displayed, as shown in the following figure.

    Figure 18: Example Application Output

    Summary

    The Sun Java Studio Creator IDE enables you to develop localized web applications specific to a single locale. Before beginningdevelopment, you must set your system and browser settings to display the target locale and language. The IDE provides propertiesand option settings to help you develop your localized application.

    The IDE also lets you develop internationalized web applications that can be automatically localized to many different locales. Therecommended way to do this is to use a properties bundle that segregates your human-readable text into one set of files for easymaintenance.See Also:

    q Creating an Internationalized Applicationq Adobe Typography Primer (PDF)

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

    This page was last modified: May 17, 2006

    18

    http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/2/demonstrating_i18n.htmlhttp://www.adobe.com/education/pdf/type_primer.pdfhttp://developers.sun.com/jscreatorhttp://developers.sun.com/jscreatorhttp://www.adobe.com/education/pdf/type_primer.pdfhttp://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/2/demonstrating_i18n.html
  • 7/30/2019 InternationaliZing Apps

    19/19

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

    q Sun Java Studio Creator integrated development environment (IDE)q Sun Java System Application Server version number(Application Server)q Java Platform, Standard Edition technology (Java SE(tm) platform)q JavaServer(tm) Faces technologyq JavaServer Pages(tm) technology (JSP(tm) technology)q Sun Java System Web Server version number(Web Server)q Java Database Connectivity software (JDBC software)q Enterprise JavaBeans(tm) specification (EJB(tm) specification)q 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 UNIX(R) softwareq 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 thisdocument. In particular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed athttp://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 itssupplements. Use is subject to license terms. Sun, Sun Microsystems, the Sun logo, Java and the Java Coffee Cup logo are trademarks orregistered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.This product is covered and controlled by U.S. ExportControl laws and may be subject to the export or import laws in other countries. Nuclear, missile, chemical biological weapons ornuclear 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 designatednationals 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 notresponsible or liable for any content, advertising, products, or other materials on or available from such sites or resources. Sun will notbe 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 suchcontent, 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 dansce document. En particulier, et ce sans limitation, ces droits de proprit intellectuelle peuvent inclure un ou plus des brevets amricainslists l'adresse http://www.sun.com/patents et un ou les brevets supplmentaires ou les applications de brevet en attente aux tats-Uniset dans les autres pays. L'utilisation est soumise aux termes de la Licence. Sun, Sun Microsystems, le logo Sun, Java et le logo JavaCoffee Cup sont des marques de fabrique ou des marques dposes de Sun Microsystems, Inc. aux tats-Unis et dans d'autres pays.Ceproduit est soumis la lgislation amricaine en matire de contrle des exportations et peut tre soumis la rglementation en vigueurdans 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'exclusiond'exportation amricaines, y compris, mais de manire non exhaustive, la liste de personnes qui font objet d'un ordre de ne pasparticiper, 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.

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

    Sun and Third-party Trademarked Terminology