struts2--struts2国际化(使用占位符)

来源:互联网 发布:函数式编程的优点 编辑:程序博客网 时间:2024/06/10 09:46

在java国际化当中,使用MessageFormat类来填充占位符,而在struts2中则采用两种更简单的方式填充:

1)在jsp页面中填充国际化消息时的占位符:

在标签<s:text>下使用<s:param>标签传递值来填充占位符

2)在Action中填充国际化消息时的占位符:

可以调用getText(String key , List args)或者getText(String key , String[] args)方法来填充占位符

实例:简单的登录系统:

登录界面:

  <body>      <s:form action = "login" method = "post">       <s:textfield name  = "username" label = "用户名"/>       <s:password name = "password" label = "密码"/>       <s:submit value = "提交"/>    </s:form>  </body>


国际化资源globalMessage_en_US.properties:

succ = {0},Welcome,you have logged in!fail = {0},Sorry,You can't log in!welcome = {0},Hello!Now is {1}!
globalMessage_zh_CN.properties

succ = {0},\u6B22\u8FCE\uFF0C\u60A8\u5DF2\u7ECF\u6210\u529F\u767B\u5F55\uFF01fail = {0},\u5BF9\u4E0D\u8D77\uFF0C\u60A8\u767B\u5F55\u5931\u8D25welcome = {0},\u60A8\u597D\uFF0C\u73B0\u5728\u65F6\u95F4\u662F {1}!




LoginAction:为了在Action中输出带有占位符的消息,在Action类中调用ActionSupport类的getText方法,并填入参数值填充占位符

package com.action;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class LoginAction extends ActionSupport{private String username;private String password;  public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String execute() {ActionContext ctx = ActionContext.getContext();if(username.equals("admin") && password.equals("admin")){ctx.getSession().put("user", username);ctx.put("tip", getText("succ",new String[]{username}));return SUCCESS;}else {ctx.put("tip", getText("fail", new String[]{username}));return SUCCESS;}}}

welcome.jsp输出页面:为了在jsp页面输出带参数的占位符,需要使用到上面提过的<s:text/>和字标签<s:param/>

  <body>    ${requestScope.tip}<br><br>    <jsp:useBean id= "date" class = "java.util.Date" scope = "page"/>    <s:text name="welcome">      <s:param>        <s:property value = "username"/>      </s:param>            <s:param>${date}</s:param>    </s:text>  </body>
struts.xml配置:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"    "http://struts.apache.org/dtds/struts-2.1.7.dtd">        <struts>     <constant name="struts.custom.i18n.resources" value="globalMessage"/>          <package name="default" namespace = "/" extends="struts-default">        <action name="login" class = "com.action.LoginAction">          <result>/welcome.jsp</result>          <result name = "login">/index.jsp</result>        </action>     </package>    </struts>

实现效果: