Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of Resource Bundle Technology in Web Application Program

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "Resource Bundle Technology Analysis in Web applications". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Background Overview

With the globalization of the world economy, it is inevitable that an application needs to be used on a global scale. Traditional programming methods hard-code translatable information such as menu button labels, prompt messages, help documents and other text information in the program code, which can not well adapt to the development of globalization, poor expansibility and high maintenance cost. An application that can support globalization must implement a single executable program and use resources (Single Source Single Executable) dynamically. Figure 1 is a comparison of the two models.

Figure 1. Traditional program model and supporting globalization program model

For an application that supports globalization:

On the one hand, what needs to be considered is the user's language environment (we call it Language Locale): this mainly refers to translation, which works correctly in their own languages in different countries, making customers feel that the product is designed for them.

On the other hand, there is the user's cultural environment (we call it Culture Locale): it mainly deals with multicultural support, including currency, calendar, time, date, sorting, interface orientation (Bi-directional) and other display methods that conform to the habits of each country.

Figure 2 outlines how to make an application (Cramp S or Bhand S) support globalization and localization.

Figure 2. Globalized application

Combined with the project practice, this paper summarizes how Java,JSP,Dojo and HTML manage Resource Bundle in web applications, and realizes a single executable program to dynamically read resource files, so as to support globalization and localization. It is mainly described from three aspects: the storage and naming rules of resource files; the reading of regional information of user language; and how to obtain the key value in the resource file of the corresponding language.

Resource Bundle Management in Java Program

ResourceBundle is a mechanism that is mainly used to display different interface text to the user according to the user's locale, making the user feel that the application is customized for me.

However, ResourceBundle in Java is a class that is included in the standard Java distribution. Figure 3 summarizes the management mechanism of ResourceBundle in the Java program.

Figure 3. Java program Resource Bundle management flow

Storage and naming of Resource Files in Java Program

In a multi-module Java application, each module usually has its own independent resource file (also known as Resource Bundles), and the Resource Bundle is generally stored in the src/resources/bundles/java/ directory of the corresponding module. The usual naming rule is: module name _ language _ country .properties ({moduleName} _ {language} _ {country} .properties). Each key in the corresponding resource file usually begins with a lowercase letter, underscores the hierarchical structure of the key in the program, and sorts it alphabetically, making it easy to manage and find, as shown in listing 1.

Listing 1. Example of a Java properties file

English Properties file: helloKey=Hello! GoodMorningKey=Good Morning! GoodEveningKey=Good Evening! Japanese Properties file: helloKey=\ u3053\ u3093\ u306b\ u3061\ u306f! GoodMorningKey=\ u304a\ u306f\ u3088\ u3046! GoodEveningKey=\ u3053\ u3093\ u3070\ u3093\ u306f!

The rollback mechanism of the Java program to the resource file: when the corresponding translated resource file does not exist, the "default" resource file (usually in English) is used. Figure 4 shows how the Java resource file is organized.

Figure 4. How Java resource files are organized

Reading of user language Environment (Locale) and Resource Files in Java

Decide which Resource Bundle to read the corresponding key value from according to the region information used by the user. The Java language represents a region through a java.util.Locale class, and a Locale instance represents a specific region. In a real project, the read resource file is usually wrapped into a class to facilitate the reuse and management of subsequent code, as shown in the example in listing 2.

Listing 2. ResourceBundleService usage in Java

Public class LocalizedPropertyResources extends MessageResources {private static final String MODULE_NAME = "resourceBundle.module.name"; public String getProperty (String key, Object... Parameters) {Locale locale = getUserLocale (); String value = getProperty (key, locale, parameters); Return value;} public String getProperty (String key, Locale locale, Object...) Parameters) {ResourceBundle resourceBundle = ResourceBundle.getBundle (MODULE_NAME, locale); String value resourceBundle.getString (key, parameters); return value;}}

Resource Bundle Management in JSP

Resource file management: JSP is based on Java technology, so the ResourceBundle mechanism in Java can also be applied to JSP. Similarly, resource files are stored in the form of .properties. The naming rules of resource files, the storage structure of resource files, and the naming rules of key can all follow the ResourceBundle management mechanism in Java programs.

User locale setting: the HTTP protocol transmits localization information from the browser to the server through the Accept-Language request header, and the custom tags in the JSTL fmt library will use these methods to automatically determine the user's locale and adjust their output accordingly. At the same time, users can also set the user language environment through.

There are three situations for reading resource files in JSP:

1. Use fmt message tags: the fmt tags in the JSP Standard tag Library (JSP Standard Tag Library,JSTL) support the localization of text content through resource files (ResourceBundle), which can respond to a specific language request. It uses J2SE's ResourceBundle to maintain various translated language codes. It is also used to set the locale, for example, this is tantamount to setting the language and country code. The default JPS reads Accept-Language information. You can also specify ResourceBundle, such as:. Once locale (region) or ResourceBundle is set, you can use it to convert the original text accordingly, and you can also use the

< fmt:requestEncoding/>

To set the requested character encoding. As shown in the example in listing 3:

Listing 3. Example of a JSTL fmt tag

/ / myTest.jsp JSTL fmt: Localized tag testing / / you can also get resource files in the following ways. ...

2. For JSP managed by Spring, there is usually such a taglig "" in JSP, in which case the Spring message tag can be used.

3. For the JSP provided by the Struts operation class, you can use the Struts bean message tag:

Resource Bundle Management in Dojo

Dojo is a JavaScript library that provides a useful tool to create a rich Web client interface. At the same time, Dojo also provides API support for globalization features, such as translation resource packs, function formatting and parsing dates, numbers and currencies. Dojo's support for globalization is mainly based on the use of CLDR (Common Locale Data Repository) and ICU. This section summarizes the management of resource files in Dojo, user area information (locale), and the reading of resource files, as shown in figure 5.

Figure 5. Resource file management in Dojo

Storage and naming of Resource Files in Dojo

UTF-8 is a prerequisite for Dojo program coding, and Dojo scripts will generally be written in HTML,JSP,Servlet,js, etc., so these files must be encoded in UTF-8. Dojo organizes resource files in JSON format. First, there is a main resource file (usually in English) in the / nls directory. The supported zone is defined in the main resource file, and the value of the region is set to true or false, as shown in listing 4.

Listing 4. Definition of the Dojo main resource file

Define ({root: {OK: "Ok", CANCEL: "Cancel", OK_CANCEL: "${OK}, ${CANCEL}"}, "ko": true, "ja": true, "ru": false, "zh-cn": true})

The translated resource files should be placed in the / nls / directory, and the directory should be named in accordance with the following specifications:

Directory names must be all lowercase

Separate languages and countries with hyphens (instead of underscores), such as zh-cn,zh-tw, as shown in listing 5.

Listing 5. Directory structure of translation resource files

/ src/web/js/nls/menu.js... The main resource file for the default message display / src/web/js/nls/ko/menu.js... Korean translation file / ja/menu.js. Japanese translation file / ru/menu.js. Russian translation file / zh-cn/menu.js. The translated document in Jane.

The rollback mechanism for Dojo resource files is that if a locale is detected in the root directory of the / nls directory, but there are no locale-specific resources in the nls directory, the main package will be used, and when a language in the main resource file is set to false, the main package will be used even if that language resource file exists.

Reading of user language Environment (Locale) and Resource Files in Dojo

Dojo and Java support user region information in the same way, but there are slight differences between Dojo and Java implementations.

"Dojo and Java have some differences in locale naming conventions. Dojo uses"-"(hyphen) as the delimiter for connecting language codes, country codes, and variants, while Java uses" _ "(underscore). For example," zh_CN "in Java is similar to" zh-cn "in Dojo.

Like the default user language zone in Java, Dojo has a global variable dojo.locale to store the default locale value, but we can't modify dojo.locale directly. We can initialize dojo.locale through dojoConfig.locale.

If dojoConfig.locale is not defined, Dojo uses the browser's display language as the user locale. In addition, the setting of dojoConfig.locale needs to be set before dojo.js is loaded, so that the set dojoConfig.locale will have an effect. Listing 6 is an example of saving the user's locale information in sessionScope and passing it to dojoConfig.

Listing 6. Save the user locale in sessionScope and pass it to dojoConfig

Var dojoConfig = {async: 'sync', baseUrl:', locale:'${sessionScope.userLanguageLocale}', bindEncoding: "utf-8",... }

UserLanguageLocale: the locale set by the user in the application, and each application may be different.

There are two ways to read resource files in Dojo:

Method 1: also known as AMD way, through dojo/i18n! The plug-in loads the resource file, first detects whether dojoConifg.locale is set, and reads dojoConfig.locale if it is set, otherwise it will read the corresponding translation resource file using the browser's display language. Listing 7 is dojo/i18n! An example of the use of

Listing 7. Dojo/i18n! Use the example

... Dojo.require ("dojo.i18n"); dojo.requireLocalization ("js", "menu"); var resources = dojo.i18n.getLocalization ("js", "menu", locale); / or omit the locale parameter, var resources = dojo.i18n.getLocalization ("js", "menu") alert (resources.OK);

Resource Bundle Management in HTML

Hard Code in HTML is usually divided into two cases: one is that the HTML page does not involve any programming logic, and you can translate the entire HTML file (this way no special processing is required during development), or change the HTML to JSP, so that the Hard Code can be extracted using the fmt tag in JSP, as shown in the example in listing 9.

Listing 9. HTML changed to JSP

/ / Index.html _ window.location = "/ login.do"; Welcome Page... / / change Index.html to Index.jsp so that you can take advantage of the fmt tag in JSP. ... / / test.properties Common_welcome=Welcome Page...

/ / change Index.html to Index.jsp so that you can take advantage of the fmt tag in JSP

Another case is that HTML is used as a Dojo widget template file, in which case dojo API's i18n library can be used to deal with hard-coded messages, which is very similar to Dojo. The Key used in the template HTML file needs to be defined and obtained in the js file of Widget. The following is an example of how to extract hard code information from HTML as a Dojo template file. The string extraction from the template HTML file is usually completed in three steps.

* * step: put the strings in HTML into a resource file such as message.js, which is organized in the same way as Dojo

Step 2: use Dojo Resource Bundle in the js file of Dojo widget to get the resource file, and define variables to get the corresponding key value.

Step 3: use the variables defined in the Dojo .js file in the HTML template file. As shown in listing 10.

Listing 10. HTML as a Dojo Widget template

Test.html Username: / / variable reference after the original hard code ${usernameLabel} / / Resource out. . Test.js dojo.requireLocalization ("js", "message"); dojo.declare ("Test") {templatePath: dojo.moduleUrl ("common", "/ html/Test.html"), usernameLabel: ", postMixInProperties: function () {this.inherited (arguments); var resources = dojo.i18n.getLocalization (" js "," message "); this.usernameLabel = resources.labels.username; / / get resource file}

Listing 11. Special hard-coding processing in HTML

/ / Hard Code Is Not Is / / this is the end of the processed HTML ${Label.IS_NOT} ${Label.IS} "Resource Bundle Technology Analysis in Web applications". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 286

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report