Struts 2 与 i18n 示例教程

17 Mar 2025 | 阅读 2 分钟

i18n 拦截器为您的应用程序提供多语言支持。

它处理为 action 设置 locale。如果用户想要设置他/她的 locale 并根据提供的 locale 获取数据,可以使用它。

默认情况下,它在 defaultStack 中找到,因此您不必显式指定它。


i18n 拦截器的参数

为 i18n 拦截器定义了 2 个参数。两者都是可选的。

参数描述
parameterName它指定 HTTP 请求参数的名称。 默认情况下,它设置为 request_locale
attributeName指定会话密钥的名称以存储区域设置。 默认情况下,它是 WW_TRANS_I18N_LOCALE

i18n 拦截器的例子

在此示例中,我们将创建以下页面

  1. Login.java
  2. Login_en.properties 和 Login_hi.properties
  3. struts.xml
  4. index.jsp
  5. login-success.jsp

1) 创建 action 类

要使用 i18n 拦截器,您需要扩展实现 TextProvider 的 ActionSupport 类。

Login.java

2) 创建属性文件

现在在包内创建 2 个属性文件。它的名称应该是 actionname_languagecode.properties。

Login_en.properties
Login_hi.properties

3) 创建 index.jsp 用于输入

此 jsp 页面使用 struts UI 标签创建一个表单。 它接收用户的姓名。

index.jsp

在 struts.xml 中定义 action

struts.xml

4) 创建视图组件

现在使用 text 标签来获取数据。 它在 i18n 中使用。

login-success.jsp

Eclipse IDE 中的目录结构

i18n directory structure

输出

struts 2 i18n example output 1 struts 2 i18n example output 2

现在让我们更改语言代码。 在这里,我们使用 chrome 浏览器。

单击设置。

struts 2 i18n example output 3

现在,单击显示高级设置。

struts 2 i18n example output 4

现在,单击语言和输入设置。

struts 2 i18n example output 5

现在,添加印地语并将它移动到顶部,然后单击完成。

struts 2 i18n example output 6

如果再次运行应用程序,它将显示印地语消息。

struts 2 i18n example output 7 struts 2 i18n example output 8

如果在 index.jsp 文件中使用 request_locale 属性名称,则消息将根据给定的语言代码显示。

让我们看看输出。

struts 2 i18n example output 9 struts 2 i18n example output 10
struts 2 i18n example output 11 struts 2 i18n example output 12