struts2国际化---配置国际化全局资源文件并输出国际化资源信息

我们首先学习怎么配置国际化全局资源文件。并输出资源文件信息

1.首先struts2项目搭建完毕后,我们在src文件夹下。即struts2.xml同级文件夹下创建资源文件。资源文件的名称格式为:

XXX_语言_国家.properties

XXX:资源文件名。能够任意定义

语言、国家:必须是java所支持的语言和国家。比如:

中国大陆:语言   zh   国家  CN

美国:语言  en   国家 US

所以我们能够这么取名:

比如:itheima_zh_CN.properties

itheima_en_US.properties

2.创建上述的两个资源文件,然后在当中输入内容:key   和   value

比如:welcome_zh_CN.properties中输入:welcome=欢迎来到北京,当中中文他们会自己主动转换为ascii码:

welcome=u6B22u8FCEu6765u5230u5317u4EAC

welcome_en_US.properties中输入:welcome=welcome to beijing

3.然后我们在struts2.xml中配置全局资源文件

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

这里value取值为itheima

4.在action中我们能够通过getText("welcome")获取值

在jsp中我们能够通过<s:text name="welcome"></s:text>标签获取值

或者<s:textfield name="" value="" key="welcome"></s:textfield>


源码:

MyAction.java:

package com.itheima.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class MyAction extends ActionSupport {

	public String execute() {
		ActionContext.getContext().put("msg", getText("welcome"));
		return "success";
	}
}
struts2.xml:

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

> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="itheima"></constant> <package name="default" namespace="/" extends="struts-default"> <action name="myAction" class="com.itheima.action.MyAction"> <result name="success">/welcome.jsp</result> </action> </package> </struts>


welcome.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!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>
	<!-- 第一种获取方式 -->
	<s:text name="welcome"></s:text><br>
	<!-- 另外一种获取方式 -->
	<s:textfield name="" value="" key="welcome"></s:textfield><br>
	<!-- 第三种获取方式:在action中通过getText("welcome")获取数据,然后放到request域中。在jsp中通过el表达式读取 -->
	${msg }<br>
</body>
</html>

项目树例如以下:


原文地址:https://www.cnblogs.com/yutingliuyl/p/6855773.html