Struts 2 預設使用 XHTML 主題。以 <s:textfield name="name" label="Name" /> 為例,生成的 HTML 結構為:
<tr>
<td class="tdLabel">
<label for="empinfo_name" class="label">Name:</label>
</td>
<td>
<input type="text" name="name" value="" id="empinfo_name"/>
</td>
</tr>
其中 empinfo 為 struts.xml 中定義的 action 名稱。
theme="xhtml"themethemethemethemethemestruts.properties 中的 struts.ui.theme(預設 xhtml)每個 Struts 標籤對應一個模板文件(如 text.ftl, password.ftl),預設打包在 struts2-core-x.y.z.jar 中。
Struts 2 標籤 + 關聯模板文件 = 最終 HTML 標記碼
模板引擎預設為 FreeMarker(.ftl),亦可切換 Velocity (.vm) 或 JSP (.jsp),透過 struts.ui.templateSuffix 與 struts.ui.templateDir 配置。
template/xhtml 到 WebContent/WEB-INF/classes/template/mythemecontrol.ftl 簡化表單結構(如移除 table 包裹)form.ftl 引用自訂 control.ftl:<#include "/${parameters.templateDir}/mytheme/control.ftl" />struts.properties 設定:struts.ui.theme=mytheme struts.ui.templateDir=template struts.ui.templateSuffix=ftl
檔案命名:bundlename_language_country.properties(如 global_zh_TW.properties)
Struts 搜尋順序:
# global.properties (預設 en_US) global.name = Name global.age = Age global.submit = Submit global.heading = Select Locale global.success = Successfully authenticated # global_zh_TW.properties global.name = 姓名 global.age = 年齡 global.submit = 提交 global.heading = 選擇語系 global.success = 認證成功 # global_ja_JP.properties global.name = 名前 global.age = 年齢 global.submit = 送信 global.heading = ロケール選択 global.success = 認証成功
| 方式 | 語法範例 | 適用場景 |
|---|---|---|
<s:property> | <s:property value="getText('global.heading')" /> | 任意位置輸出 |
<s:text> | <s:text name="global.heading" /> | 簡單訊息顯示 |
<s:i18n> | <s:i18n name="some.package.bundle"><s:text name="key" /></s:i18n> | 指定資源包作用域 |
UI 標籤 key 屬性 | <s:textfield key="global.name" name="username"/> | 表單標籤自動取 label |
index.jsp - 語系切換連結與表單:
<s:url id="indexEN" namespace="/" action="locale">
<s:param name="request_locale">en</s:param>
</s:url>
<s:a href="%{indexEN}">English</s:a>
<s:a href="%{indexES}">Spanish</s:a>
<s:a href="%{indexFR}">France</s:a>
<s:form action="empinfo" method="post" namespace="/">
<s:textfield name="name" key="global.name" size="20" />
<s:textfield name="age" key="global.age" size="20" />
<s:submit name="submit" key="global.submit" />
</s:form>
Action 類別:
// 語系切換 Action
public class Locale extends ActionSupport {
public String execute() { return SUCCESS; }
}
// 表單提交 Action
public class Employee extends ActionSupport {
private String name;
private int age;
// getter/setter 省略
public String execute() { return SUCCESS; }
}
struts.xml:
<constant name="struts.custom.i18n.resources" value="global" />
<package name="helloworld" extends="struts-default" namespace="/">
<action name="locale" class="com.example.Locale">
<result name="success">/index.jsp</result>
</action>
<action name="empinfo" class="com.example.Employee">
<result name="success">/success.jsp</result>
</action>
</package>
部署後訪問 https://localhost:8080/HelloWorldStruts2/index.jsp 即可體驗多語言切換效果。
global.properties 統一管理應用層訊息,搭配 struts.custom.i18n.resources 全域載入。