使用Struts2怎么实现国际化

发布时间:2021-04-15 17:31:31 作者:Leah
来源:亿速云 阅读:163

今天就跟大家聊聊有关使用Struts2怎么实现国际化,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

第一步:在src目录下添加两个资源文件,命名方式很重要的。格式:baseName_language_country.properties。还有两种命名方式,都可以的,这个不用过多研究。比如,实现中英文切换我们要添加 resource_zh_CN.properties 和 resource_en_US.properties。然后将各个key-value对添加到这两个文件中,key字段一定要统一。如:

使用Struts2怎么实现国际化 

使用Struts2怎么实现国际化     

其中,value值可以使用占位符,比如:你好{0},至于怎么传参数,稍后再解释。

第二步:配置struts.properties文件,这个文件也是放在src目录下的。

使用Struts2怎么实现国际化

第一个键值对是为了告诉程序,国际化资源文件是loginResource开头命名的资源文件。

到这里其实配置就算完事儿了,接下来就是在各个地方使用。

(1)在jsp中使用。举两个例子。

<s:text name="login.title"></s:text>
<s:textfield name="username" key="login.username"></s:textfield>

还可以输出带占位符的信息。如,有一个 login.welcome = 你好{0},那么可以用下面这种方式来显示:

<s:text name="login.welcome"><s:param><s:property value="username"/></s:param></s:text>

(2)在Action中使用。举个例子:

getText("login.username");

还可以使用带占位符的信息。如,有一个 login.welcome = 你好{0},那么可以用下面这种方式来显示:

String params[] = {"张三"};

String welcome = getText("login.welcome", params);

第三步,实现在jsp页面中的中英文切换。

index.jsp中主要部分代码如下:

<a href="lang.action?request_locale=zh_CN" rel="external nofollow" >中文</a>
   <a href="lang.action?request_locale=en_US" rel="external nofollow" >English</a>
   
   <s:form id="loginform" action="login" method="post">
     <s:textfield name="username" key="login.username"></s:textfield>
     <s:textfield name="psd" key="login.psd" ></s:textfield>
     <s:submit key="login.submit"></s:submit>
   </s:form>

主要看前两行代码,lang.action其实就是一个实现页面转换的Action,没有什么实质性的内容,随便定义一个HelloAction.java,在execute()方法中返回个success就行了。url中的这个参数 request_locale会被 i18n 拦截器读取,然后根据这个值设置语言环境。 i18n 拦截器是struts中default里面自带的拦截器。

struts.xml配置如下:

<action name="login" class="com.main.action.LoginAction">
      <exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
      <result name="success">/success.jsp</result>
      <result name="error">/index.jsp</result>
      <result name="input">/index.jsp</result>
      <result name="regist">/regist.jsp</result>  
    </action>
    
    <action name="lang" class="com.main.action.HelloAction">
      <result name="success">/index.jsp</result>
    </action>

看完上述内容,你们对使用Struts2怎么实现国际化有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. struts2 自实现
  2. SpringBoot怎么实现国际化过程

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

struts2

上一篇:php中的加密解密功能函数有哪些

下一篇:怎么在iOS中获取系统iTunes音乐

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》