我们首先学习怎么配置国际化全局资源文件。并输出资源文件信息
1.首先struts2项目搭建完毕后,我们在src文件夹下。即struts2.xml同级文件夹下创建资源文件。资源文件的名称格式为:
XXX_语言_国家.properties
XXX:资源文件名。能够任意定义
语言、国家:必须是java所支持的语言和国家。比如:
中国大陆:语言 zh 国家 CN
美国:语言 en 国家 US
所以我们能够这么取名:
比如:itheima_zh_CN.properties
itheima_en_US.properties
2.创建上述的两个资源文件,然后在当中输入内容:key 和 value
比如:welcome_zh_CN.properties中输入:welcome=欢迎来到北京,当中中文他们会自己主动转换为ascii码:
welcome=\u6B22\u8FCE\u6765\u5230\u5317\u4EAC
welcome_en_US.properties中输入:welcome=welcome to beijing
3.然后我们在struts2.xml中配置全局资源文件
<constant name="struts.custom.i18n.resources" value="XXX"></constant>
这里value取值为itheima
4.在action中我们能够通过getText("welcome")获取值
在jsp中我们能够通过<s:text name="welcome"></s:text>标签获取值
或者<s:textfield name="" value="" key="welcome"></s:textfield>
源码:
MyAction.java:
package com.itheima.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class MyAction extends ActionSupport {
public String execute() {
ActionContext.getContext().put("msg", getText("welcome"));
return "success";
}
}
struts2.xml:
> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="itheima"></constant> <package name="default" namespace="/" extends="struts-default"> <action name="myAction" class="com.itheima.action.MyAction"> <result name="success">/welcome.jsp</result> </action> </package> </struts>
welcome.jsp:
项目树例如以下: