Struts 2 简明教程

Struts2 - Localization, internationalization (i18n)

国际化 (i18n) 是规划和实施产品和服务以便它们可以轻松适应特定当地语言和文化的过程,这一过程称为本地化。国际化流程称为翻译或本地化支持。

Internationalization (i18n) is the process of planning and implementing products and services so that they can easily be adapted to specific local languages and cultures, a process called localization. The internationalization process is called translation or localization enablement.

国际化缩写为 i18n ,因为该单词以字母 “i” 开头,以 “n” 结尾,并且在第一个 i 和最后一个 n 之间有 18 个字符。

Internationalization is abbreviated i18n because the word starts with the letter “i” and ends with “n”, and there are 18 characters between the first i and the last n.

Struts2 提供本地化,即,通过以下位置的资源包、拦截器和标签库来提供国际化 (i18n) 支持 −

Struts2 provides localization, i.e., internationalization (i18n) support through resource bundles, interceptors and tag libraries in the following places −

  1. The UI Tags

  2. Messages and Errors.

  3. Within action classes.

Resource Bundles

Struts2 使用资源包为 Web 应用程序的用户提供多种语言和区域设置选项。您不必担心用不同语言编写页面。您所要做的就是为所需的每种语言创建一个资源包。资源包将包含在其用户语言中的标题、消息和其他文本。资源包是包含应用程序默认语言的关键/值对的文件。

Struts2 uses resource bundles to provide multiple language and locale options to the users of the web application. You don’t need to worry about writing pages in different languages. All you have to do is to create a resource bundle for each language that you want. The resource bundles will contain titles, messages, and other text in the language of your user. Resource bundles are the file that contains the key/value pairs for the default language of your application.

资源文件的命名格式最简单:

The simplest naming format for a resource file is −

bundlename_language_country.properties

在此处, bundlename 可以是 ActionClass、Interface、SuperClass、Model、Package、全局资源属性。下一部分 language_country 代表国家/地区语言环境,例如,西班牙语(西班牙)语言环境由 es_ES 表示,英语(美国)语言环境由 en_US 等表示,其中您可以跳过国家/地区部分(这是可选的)。

Here, bundlename could be ActionClass, Interface, SuperClass, Model, Package, Global resource properties. Next part language_country represents the country locale for example, Spanish (Spain) locale is represented by es_ES, and English (United States) locale is represented by en_US etc. where you can skip country part which is optional.

当您按其键引用一个消息元素时,Struts 框架按以下顺序搜索相应的讯息包 −

When you reference a message element by its key, Struts framework searches for a corresponding message bundle in the following order −

  1. ActionClass.properties

  2. Interface.properties

  3. SuperClass.properties

  4. model.properties

  5. package.properties

  6. struts.properties

  7. global.properties

要使用多种语言进行开发应用程序,您应该维护对应于那些语言/区域设置的多个属性文件,并根据关键/值对定义所有内容。

To develop your application in multiple languages, you should maintain multiple property files corresponding to those languages/locale and define all the content in terms of key/value pairs.

例如,如果你准备为美式英语(默认)、西班牙语和法语开发你的应用程序,那么你将必须创建三个属性文件。这里我仅使用 global.properties 文件,但你也可以利用不同的属性文件来分离不同类型的消息。

For example, if you are going to develop your application for US English (Default), Spanish, and French, then you would have to create three properties files. Here I will use global.properties file only, you can also make use of different property files to segregate different type of messages.

  1. global.properties − By default English (United States) will be applied

  2. global_fr.properties − This will be used for Franch locale.

  3. global_es.properties − This will be used for Spanish locale.

Access the messages

有许多种方法可以访问消息资源,包括 getText、text 标记、UI 标记的 key 属性以及 i18n 标记。我们简要了解下它们−

There are several ways to access the message resources, including getText, the text tag, key attribute of UI tags, and the i18n tag. Let us see them in brief −

如需显示 i18n 文本,请在属性标记或任何其他标记(如 UI 标记)中调用 getText ,如下所示−

To display i18n text, use a call to getText in the property tag, or any other tag, such as the UI tags as follows −

<s:property value = "getText('some.key')" />

text tag 从默认资源包(即 struts.properties)中检索一条消息

The text tag retrieves a message from the default resource bundle, i.e., struts.properties

<s:text name = "some.key" />

i18n tag 将任意资源包推送到值栈。i18n 标记作用域范围内的其他标记可显示该资源包中的消息−

The i18n tag pushes an arbitrary resource bundle on to the value stack. Other tags within the scope of the i18n tag can display messages from that resource bundle−

<s:i18n name = "some.package.bundle">
   <s:text name = "some.key" />
</s:i18n>

大多数 UI 标记的 key 属性可用于从资源包生成消息−

The key attribute of most UI tags can be used to generate a message from a resource bundle −

<s:textfield key = "some.key" name = "textfieldName"/>

Localization Example

让我们把目标设定为从前一章节中用多种语言创建 index.jsp 。相同的文件将按如下方式编写−

Let us target to create index.jsp from the previous chapter in multiple languages. Same file would be written as follows −

<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
   pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
   <head>
      <title>Employee Form with Multilingual Support</title>
   </head>

   <body>
      <h1><s:text name = "global.heading"/></h1>

      <s:url id = "indexEN" namespace="/" action = "locale" >
         <s:param name = "request_locale" >en</s:param>
      </s:url>

      <s:url id = "indexES" namespace="/" action = "locale" >
         <s:param name = "request_locale" >es</s:param>
      </s:url>

      <s:url id = "indexFR" namespace="/" action = "locale" >
         <s:param name = "request_locale" >fr</s:param>
      </s:url>

      <s:a href="%{indexEN}" >English</s:a>
      <s:a href="%{indexES}" >Spanish</s:a>
      <s:a href="%{indexFR}" >France</s:a>

      <s:form action = "empinfo" method = "post" namespace = "/">
         <s:textfield name = "name" key = "global.name" size = "20" />
         <s:textfield name = "age" key = "global.age" size = "20" />
         <s:submit name = "submit" key = "global.submit" />
      </s:form>

   </body>
</html>

我们将创建 success.jsp 文件,在已定义的操作返回 SUCCESS 的情况下,将会调用该文件。

We will create success.jsp file which will be invoked in case defined action returns SUCCESS.

<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
	pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
   <head>
      <title>Success</title>
   </head>

   <body>
      <s:property value = "getText('global.success')" />
   </body>
</html>

在这里,我们需要创建以下两个操作。(a) 第一个操作 (a) 负责处理地区设置并显示具有不同语言的相同 index.jsp 文件 (b) 另一个操作负责处理提交表单本身。两个操作都将返回 SUCCESS,但我们将根据返回的值采取不同的操作,因为两个操作的目的不同

Here we would need to create the following two actions. (a) First action a to take care of Locale and display same index.jsp file with different language (b) Another action is to take care of submitting form itself. Both the actions will return SUCCESS, but we will take different actions based on return values because our purpose is different for both the actions

Action to take care of Locale

package com.tutorialspoint.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class Locale extends ActionSupport {
   public String execute() {
       return SUCCESS;
   }
}

Action To Submit The Form

package com.tutorialspoint.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class Employee extends ActionSupport{
   private String name;
   private int age;

   public String execute() {
      return SUCCESS;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public int getAge() {
      return age;
   }

   public void setAge(int age) {
      this.age = age;
   }
}

现在让我们创建以下三个 global.properties 文件,并将其放入 CLASSPATH 中 −

Now let us create the following three global.properties files and put the in CLASSPATH

global.properties

global.name = Name
global.age = Age
global.submit = Submit
global.heading = Select Locale
global.success = Successfully authenticated

global_fr.properties

global.name = Nom d'utilisateur
global.age = l'âge
global.submit = Soumettre des
global.heading = Sé lectionnez Local
global.success = Authentifi	é  avec succès

global_es.properties

global.name = Nombre de usuario
global.age = Edad
global.submit = Presentar
global.heading = seleccionar la configuracion regional
global.success = Autenticado correctamente

我们将使用两个操作创建 struts.xml ,如下所示−

We will create our struts.xml with two actions as follows −

<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <constant name = "struts.devMode" value = "true" />
   <constant name = "struts.custom.i18n.resources" value = "global" />
   <package name = "helloworld" extends = "struts-default" namespace="/">
      <action name = "empinfo"
         class = "com.tutorialspoint.struts2.Employee"
         method = "execute">
         <result name = "input">/index.jsp</result>
         <result name = "success">/success.jsp</result>
      </action>

      <action name = "locale"
         class = "com.tutorialspoint.struts2.Locale"
         method = "execute">
         <result name = "success">/index.jsp</result>
      </action>
   </package>

</struts>

以下是 web.xml 文件的内容:

Following is the content of web.xml file −

<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns = "http://java.sun.com/xml/ns/javaee"
   xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id = "WebApp_ID" version = "3.0">

   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>

   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

现在,右键单击项目名称并单击 Export > WAR File 以创建 War 文件。然后将此 WAR 部署在 Tomcat 的 webapps 目录中。最后,启动 Tomcat 服务器并尝试访问 URL http://localhost:8080/HelloWorldStruts2/index.jsp 。这将生成以下屏幕:

Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen −

helloworldstruts14

现在选择任何一种语言,我们假设选择 Spanish ,它将显示以下结果−

Now select any of the languages, let us say we select Spanish, it would display the following result −

helloworldstruts15

你也可以尝试使用法语。最后,让我们尝试在我们处于西班牙语地区设置时,单击 Submit 按钮,它将显示以下屏幕−

You can try with French language as well. Finally, let us try to click Submit button when we are in Spanish Locale, it would display the following screen −

helloworldstruts16

恭喜你,现在你拥有了一个多语言网页,可以面向全球推出你的网站。

Congratulations, now you have a multi-lingual webpage, you can launch your website globally.