First, we will learn how to configure global resource files and output resource file information.
1. After the struts2 project is set up, create a resource file under the src directory, that is, the struts2.xml directory at the same level. The name format of the resource file is as follows:
Xxx _ language _ country. Properties
XXX: resource file name, which can be defined at will
Language and country: the language and country supported by Java, for example:
Mainland China: Language en CN
US: Language en country us
So we can name it like this:
Example: itheima_zh_cn.properties
Itheima_en_us.properties
2. Create the preceding two resource files and enter the key and Value
For example, in welcome_zh_cn.properties, enter: Welcome = welcome to Beijing, where Chinese characters are automatically converted to ASCII codes:
Welcome = \ u6b22 \ u8fce \ u6765 \ u5230 \ u5317 \ u4eac
Welcome_en_us.properties: Welcome = welcome to Beijing
3. Configure the global resource file in struts2.xml.
<Constant name = "struts. Custom. i18n. Resources" value = "XXX"> </constant>
Here, the value is itheima.
4. In the action, we can get the value through gettext ("welcome ").
In JSP, we can use the <s: Text name = "welcome"> </S: Text> label to obtain the value.
Or <s: textfield name = "" value = "" Key = "welcome"> </S: textfield>
Source code:
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>
The project tree is as follows:
Struts2 internationalization-configure the internationalized global resource file and output the internationalized Resource Information