这节我们将讲述的是struts2中的properties文件的一些使用方法。
我们将会使用的是之前的一个register包下的注册这样一个流程,来讲解properties的使用方法。
首先我们先需要建立一个properties file
package:org.apache.struts.register.action
ActionName:RegisterAction.java
PropertiesName:RegisterAction.properties 保持类名一致性
personBean.firstName=First name
personBean.lastName=Last name
personBean.age=Age
personBean.email=Email
thankyou=Thank you for registering %{personBean.firstName}.
上面是一个标准的java辅助文件。关键词在左边,右边是对应javabean里的名字
thankyou里面很明显使用了EL,说明OGNL是在request层包装dispatcher的。。。
题外话:其实这东西可以无视。。用JSTL+JSON也可以很顺利的完成。。就可以扔掉struts tag了。。。当然其实他做的也很好。。。下面几篇会扯点关于这个。。
之前的Register的s:textfield
<s:textfield name="personBean.firstName" label="First Name" size="11"></s:textfield>
现在因为加入了properties的支持,我们可以简化成
<s:textfield key="personBean.firstName" size="11"></s:textfield>
在thankyou.jsp中修改标题
<h3><s:text name="thankyou" /></h3>
好了。我们来试试
struts的拦截器忘记+了
在struts.xml文件中加入一个action
<action name="registerInput" class="org.apache.struts.register.action.RegisterAction" method="input">
<result name="input">/Register.jsp</result>
</action>
修改index.jsp中的跳转链接
之前我们用的都是href直接跳转,现在要加上s tag
<s:url action="registerInput" var="registerInputLink"/>
<p><a href="${registerInputLink}">Register now!</a></p>
这样应该就过去了~
Global Properties:
请在src下或者main/src下(不同版本,ant下src,Maven下src/main/resource)
注意,文件名并不一定要取名为global
contact=For assistance contact <a href='mailto:contact@email.com'>contact@email.com</a>
在struts.xml中加入global properties
<constant name="struts.custom.i18n.resources" value="global" />
这样就可以使用全范围辅助文本了。
我们在首页index.jsp最下方加入
<hr />
<s:text name="contact" />
完毕
全球语言性质的properties
比如我们本地语言是en的但是我希望他出现的语言是西班牙语。
这样的话我们就要进行修改文本了。很幸运,struts2提供了这么一个途径可以很方便修改这事
example:
personBean.firstName=Nombre
personBean.lastName=Apellidos
personBean.age=Edad
personBean.email=Correo
thankyou=Gracias por registrarse, %{personBean.firstName}.
把这个文件和Register.properties.放在同一位置
接下来我们就需要修改
<h3>Registro español</h3>
<s:url action="registerInput" var="registerInputLinkES">
<s:param name="request_locale">es</s:param>
</s:url>
<p></p><a href="${registerInputLinkES}">Por favor, regístrese</a> para nuestro sorteo</p>
我们试试
成功了。
要点:保持properties前面的文字和action同名,参数带的正确即可。