您的位置:首页 > 编程语言 > Java开发

Struts2之国际化

2015-02-01 18:59 309 查看
1:在Src下建立两个属性文件(注:两个文件的key值要相同)



其中内容如下

RES_en_US.properties

username=username

password=password

welcome={0} welcome to J***A world{1}

submit=submit

RES_zh_CN.properties(里面放的是中文对应的unicode编码)

username=\u7528\u6237\u540D

password=\u5BC6\u7801

welcome={0} \u6B22\u8FCE\u6765\u5230J***A\u4E16\u754C{1}

submit=\u63D0\u4EA4

2 index.jsp的核心代码

<%@ taglib uri="/struts-tags" prefix="s"%>

<body>

<a href="lang?request_locale=zh_CN">中文</a>

<a href="lang?request_locale=en_US">English</a>

<s:form action="show" method="post">

${message}

<s:textfield name="username" key="username" ></s:textfield>//username是属性文件中的key值

//JSP为占位符传参(后续加上去的运行截图显示时没有这段代码)

<s:text name="welcome">

<s:param>晓波哥</s:param>

<s:param>学习</s:param>

</s:text>

<s:submit key="submit"></s:submit>

</s:form>

</body>

3action类

(1)中英文切换对应的action

package org.action;

import com.opensymphony.xwork2.ActionSupport;

public class LangAction extends ActionSupport {

@Override

public String execute() throws Exception {

// TODO Auto-generated method stub

return SUCCESS;

}

}

(2)表单提交的action

package org.action;

import com.opensymphony.xwork2.ActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class ResAction extends ActionSupport {

private String username;

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

@Override

public String execute() throws Exception {

// action中为占位符传参


ActionContext.getContext().put("message", this.getText("welcome",new String[]{username,"学习"})) ;//页面中有个${message}获取该值,welcome是属性文件中的key值

return SUCCESS;

}

}

3struts.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

<!--下面这个全局常量说明使用属性文件进行国际化-->

<constant name="struts.custom.i18n.resources" value="RES"/>

<package name="default" extends="struts-default">

<action name="show" class="org.action.ResAction" >

<result name="success">/index.jsp</result>

</action>



<action name="lang" class="org.action.LangAction" >

<result name="success">/index.jsp</result>

</action>

</package>

</struts>

4运行截图:

(1)测试中英文切换





(2)输入用户名并且在文本框上方显示出来(中文下的就不截图了





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: