首页 > 代码库 > 国际化

国际化

在src目录下新建.properties文件如

技术分享

struts2.xml文件

<!-- 配置国际化资源文件 -->
    <constant name="struts.custom.i18n.resources" value="i18n"></constant>

 

//内容英文

username=UserName
passwword=Password
submit=Submit

time=Time:{0}//带占位符

//中文
username=\u7528\u6237\u540D
password=\u5BC6\u7801
submit=\u63D0\u4EA4

time=\u65F6\u95F4:{0}

//默认
username=UserName
password=Password
submit=Submit

time=Time:{0}

Action

package com.i18n;

import java.util.Arrays;
import java.util.Date;

import com.opensymphony.xwork2.ActionSupport;

public class TestI18nAction extends ActionSupport {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    private Date date = null;
    
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public String execute() throws Exception {
        
        date = new Date();
        
        //1. 在 Action 中访问国际化资源文件的 value 值
        String username = getText("username");
        System.out.println(username);
        
        //2. 带占位符的
        String time = getText("time", Arrays.asList(date));
        System.out.println(time);
        
        return SUCCESS;
    }
}
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    
    
    

    <a href="I18n?request_locale=en_US">English</a>
    <a href="I18n?request_locale=zh_CN">中文</a>
    <br><br>
    
    
    <br><br>

       <!--通过s:text拿到国际化文件内容-->
    <s:text name="time">
        <s:param value="date"></s:param>
    </s:text>
    
    

    
    <br><br>
    
    
    <s:form action="" theme="simple">
        
        <!--通过强制OGNL解析-->
        <s:text name="username"/>:<s:textfield name="username" label="%{getText(‘username‘)}"></s:textfield>
        
        <!-- key 的方式是直接上资源文件中获取 value 值 -->
        <s:text name="username"/>:<s:textfield name="username" key="username"></s:textfield>
        <s:text name="password"/>:<s:password name="password" key="password"></s:password>
        <s:submit key="submit" value="%{getText(‘submit‘)}"></s:submit>
            
    </s:form>
    
</body>
</html>

 技术分享

技术分享

 

国际化