读书人

Struts2课程七Message Resource F

发布时间: 2013-02-19 11:11:40 作者: rapoo

Struts2教程七——Message Resource Files

本教程假设你已完成Form Validation教程,可以在Google Code -http://code.google.com/p/struts2-examples/downloads/list下载 Message_Resource_Struts2_Ant或者Message_Resource_Struts2_Mvn。引言

本课学习使用Struts 2消息资源功能(也叫资源bundles)。消息资源提供了一个简单的在view页面中放置文本的方式,文本可以用来完成用户本地化。

消息资源属性文件

在Struts 2 web application中可以创建跟struts2 action相应的消息资源属性文件,这个文件和action同名,以.properties为后缀,本文件要与action类在同一个包目录下,本课用properties文件放置表单标签的label值,以实现不同语言之间的转换。

如果你完成了Form Validation ,可在原项目中改写。

在org.apache.struts.register.action包下建立Register.properties文件,并加入以下文本:

Register.propertiestextfield tagtextfield tag with key attributelink to register.jsplink to Register Action classregisterInput action node for struts.xml

点击register,出现register.jsp页面,代表域的label将会是Register.properties文件相应key的value值。

Struts2课程七——Message Resource Files

Struts 2 Text标签

Struts 2 text标签也可以使用properties文件,在thankyou.jsp加入以下内容取代h3标签。

text tag

那么在thankyou.jsp中怎样使用用户的输入呢?像personBean.firstName。回头看看Register.properties文件的thankyou key。

Register.propertiespackage.properties

全局的Properties

你也可以在struts.xml中配置一个全局的properties文件。这个property文件中定义的key和value值对所有action执行后返回的view页面都是可用的。

加入如下global.properties文件(文件名不强制要求为global)。

global.propertiesSpecify Global Property File In struts.xmlUsing contact property

Struts 2会先从匹配action类的properties文件中查找,如找不到,则在包级别的properties文件中查找,最后在struts.xml文件中配置的文件中查找。这里会在global文件中找到。

也可以在所有jsp页面中加入上述text标签。

国际化

使用属性资源文件可以提供不同语言的文本,默认情况下,struts 2 会使用用户的本地语言。如果本地语言为英语,则struts 2会找到没有地区标记的文件,例如Register.properties。如果本地语言非英语,例如西班牙语,则struts 2会查找Register_es.properties。

为了说明,我们创建一个Register_es.properties文件并加入以下内容(value为西班牙语)。

Register_es.propertiesSpecify The Locale As a URL Parameter

带_es的文件对于包级别的properties文件和全局的properties文件都是一样的,使用这些,我们可以建立全页面都是西班牙语的应用。

总结

学习了消息资源文件和国际化,想了解更多请参考官方文档http://struts.apache.org。

下篇

下篇教程学习配置Struts 2来处理未捕获异常。

读书人网 >编程

热点推荐