情景:对于网页的提示信息,例如:请输入账号,请输入密码这样的提示信息,不同的人开发,有可能习惯不一样,所以有必要把这些信息封装到单独的properties文件中。
举例
<h1>普通方法</h1> <html:form action="/login"> acount : <html:text property="acount"/><html:errors property="acount"/><br/> password : <html:text property="password"/><html:errors property="password"/><br/> <html:submit/><html:cancel/> </html:form> <hr>注意普通的方法必须自己在页面上写:acoutn 和 password |
<h1>资源文件方法</h1> <html:form action="/login"> <bean:message key="info.input.acount"/> <html:text property="acount"/><html:errors property="acount"/><br/> <bean:message key="info.input.password"/> <html:text property="password"/><html:errors property="password"/><br/> <html:submit/><html:cancel/> </html:form> <hr>利用资源文件的方法就是:加上一个<bean:message></bean:message>的标签 这里的key是对应着资源配置文件中等号左边的值,它显示的将是:等号右边的值 |
还可以在配置文件中添加参数
<h1>资源文件方法2</h1> <html:form action="/login"> <bean:message key="info.input" arg0="acount"/> <html:text property="acount"/><html:errors property="acount"/><br/> <bean:message key="info.input" arg0="password"/> <html:text property="password"/><html:errors property="password"/><br/> <html:submit/><html:cancel/> </html:form> <hr>这里的arg0就是参数对应的配置文件中写的{0},{1},{2},{3}参数最多是5个 这里的参数可以直接写String类型的,也可以童工el表达式来写${acount}也可以会从request或是session来读取 |
问题:在这里,如果配置文件中写了中文那么就会显示乱码
<html:form action="/login"> <bean:message key="info.input" arg0="账号" /> <html:text property="acount"/><html:errors property="acount"/><br/> <bean:message key="info.input" arg0="密码" /> <html:text property="password"/><html:errors property="password"/><br/> <html:submit/><html:cancel/> </html:form> |
解决:将配置文件有中文的分离出来,通过java/bin目录下的native2ascii这个工具将文件转化成相应的编码,例如:将ApplicationResources.properties(中文字符)转化为相应的ascii码 命令是:
D:\java\hibernate\project7_1\src\com\feidaochuanqing\struts>native2ascii -encoding gb2312 ApplicationResources.properties a.properties
注意这个命令 参数是encoding 第一个是本地文件的编码格式 第二个参数是 源文件的名称,第三个参数是 目标文件的名称
将 转化后的文件放到相应的目录下面,并且在struts-config中进行配置如下
<message-resources parameter="com.feidaochuanqing.struts.ApplicationResources" /> <message-resources key="zh_CN" parameter="com.feidaochuanqing.struts.ApplicationResources_zh_CN.properties" /> |
最好将有中文的全放到第二个文件中,并且加上关键字key 用来区分默认的文件
怎样调用第二个文件呢?
在jsp中
<html:form action="/login"> <bean:message key="info.input" arg0="账号" /> <html:text property="acount"/><html:errors property="acount"/><br/> <bean:message key="info.input" arg0="密码" /> <html:text property="password"/><html:errors property="password"/><br/> <html:submit/><html:cancel/> </html:form>注意这里的 <message 标签中不用写 bundle了 否则报错> |