struts2教程(6)--国际化处理
一、Struts2國際化介紹
1、 國際化原理?
同一款軟件 可以為不同用戶,提供不同語言界面 ?----國際化軟件
需要一個語言資源包(很多properties文件,每個properties文件 針對一個國家或者語言 ,通過java程序根據來訪者國家語言,自動讀取不同properties文件 )
2、 資源包編寫
properties文件命名 : ?基本名稱_語言(小寫)_國家(大寫).properties
例如 :
messages_zh_CN.properties 中國中文
messages_en_US.properties 美國英文
3、 ResourceBundle根據不同Locale(地域信息),讀取不同國家properties文件
ResourceBundle bundle = ResourceBundle.getBundle("messages", Locale.US);
二、國際化配置
1、第一種全局國際化信息文件?(所有Action都可以使用 )
?properties文件可以在任何包中
需要在struts.xml中配置全局信息文件位置
struts.xml
<constant name="struts.custom.i18n.resources" value="messages"></constant> messages.properties 在src根目錄<constant name="struts.custom.i18n.resources" value="com.sihai.resources.messages"></constant> messages.properties 在com.sihai.resources 包國際化信息
在Action中使用 ?:this.getText("msg");
package com.sihai.action;import com.opensymphony.xwork2.ActionSupport;public class I18nDemo1Action extends ActionSupport {@Overridepublic String execute() throws Exception {// 得到properties文件中信息.//System.out.println(this.getText("msg"));//動態文本System.out.println(this.getText("msg", new String[]{"tom"}));return NONE;} } com.sihai.action;import com.opensymphony.xwork2.ActionSupport;public class I18nDemo1Action extends ActionSupport {@Overridepublic String execute() throws Exception {// 得到properties文件中信息.//System.out.println(this.getText("msg"));//動態文本System.out.println(this.getText("msg", new String[]{"tom"}));return NONE;} }在jsp中使用 ?:<s:text name="msg" />
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head><title>My JSP 'index.jsp' starting page</title></head><body><%--<s:i18n name="com.sihai.action.package"><s:text name="nameerror"/></s:i18n>--%><%--<s:text name="name" />--%><s:i18n name="com.sihai.action.I18nDemo1Action"><s:text name="msg"><s:param>張三</s:param></s:text></s:i18n> </body> </html> com.sihai.action.package"><s:text name="nameerror"/></s:i18n>--%><%--<s:text name="name" />--%><s:i18n name="com.sihai.action.I18nDemo1Action"><s:text name="msg"><s:param>張三</s:param></s:text></s:i18n> </body> </html>在配置文件中(校驗xml) :<message key="agemsg"></message>
2、第二種 Action范圍信息文件?(只能在某個Action中使用 )
數據只能在對應Action中使用,在Action類所在包 創建Action類名.properties ?---------無需配置
?3、第三種 package范圍信息文件?(package中所有Action都可以使用 )
數據對包 (包括子包)中的所有Action都有效 , 在包中創建 package.properties -----無需配置
?4、第四種臨時信息文件?(主要在jsp中 引入國際化信息 )
在jsp指定讀取 哪個properties文件
<s:i18n name="com.sihai.struts2.demo7.package"><s:text name="customer"></s:text></s:i18n>?向信息中傳遞參數 ?{0} {1} ------------ MessageFormat動態消息文本
this.getText("required", new String[] { "用戶名" });
總結
以上是生活随笔為你收集整理的struts2教程(6)--国际化处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: struts2教程(5)--请求参数校验
- 下一篇: struts2教程(7)--拦截器