struts2实现国际化
案例:
在src目录下新建两个属性文件:
welcome_en_US.properties:
greeting=Welcome to china\!
welcome_zh_CN.properties:
greeting=欢迎来到中国
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="welcome"></constant> </struts>
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@ taglib uri="/struts-tags" prefix="s" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <s:text name="greeting"></s:text> </body> </html>
在action中访问资源文件:
User.java:
package blog.i18n; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class User extends ActionSupport { public String execute(){ ActionContext.getContext().put("wel", this.getText("greeting")); return "success"; } }
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="welcome"></constant> <package name="i18n" extends="struts-default" namespace="/person"> <action name="nation" class="blog.i18n.User" method="execute"> <result name="input">/index.jsp</result> <result name="success">/WEB-INF/message.jsp</result> </action> </package> </struts>
message.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@ taglib uri="/struts-tags" prefix="s" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <s:text name="greeting"></s:text> <br/> <%= request.getAttribute("wel") %> </body> </html>