Struts2 中 <form action="A"> 為靜態屬性,<s:if> 僅控制頁面顯示內容,**無法動態改變 form 的 action 提交目標**。無論滿足哪個條件,表單始終提交到 Action A。
<s:if test="condition1">
<!-- 顯示內容 1 -->
</s:if>
<s:elseif test="condition2">
<!-- 顯示內容 2 -->
</s:elseif>
<form action="A"> <!-- 固定 action -->
<!-- 表單字段 -->
</form>
<s:if test="condition1">
<form action="Action1">
<!-- 字段組 1 -->
<s:submit value="提交1" />
</form>
</s:if>
<s:elseif test="condition2">
<form action="Action2">
<!-- 字段組 2 -->
<s:submit value="提交2" />
</form>
</s:elseif>
<form action="DispatcherAction">
<s:hidden name="actionType" value="%{condition1 ? 'type1' : 'type2'}" />
<!-- 通用字段 -->
<s:submit />
</form>
public class DispatcherAction extends ActionSupport {
private String actionType;
public String execute() {
switch (actionType) {
case "type1": return handleType1();
case "type2": return handleType2();
default: return ERROR;
}
}
private String handleType1() { /* 邏輯1 */ return SUCCESS; }
private String handleType2() { /* 邏輯2 */ return SUCCESS; }
// getter/setter
}
<form id="dynamicForm" action="DefaultAction">
<s:radio list="{'type1':'選項1','type2':'選項2'}" name="type" onchange="changeAction(this.value)" />
<s:submit />
</form>
<script>
function changeAction(type) {
var form = document.getElementById('dynamicForm');
form.action = type === 'type1' ? 'Action1' : 'Action2';
}
</script>
| 標簽 | 執行階段 | 作用 |
|---|---|---|
| <s:if> | 頁面渲染時 | 條件顯示/隱藏頁面片段 |
| <form> | 頁面渲染時 | 生成 HTML <form action="..."> |
| Action 執行 | 表單提交後 | 服務端處理業務邏輯 |
頁面渲染階段確定的屬性 (action/method) 無法在渲染後動態改變,必須在渲染時生成正確的 HTML,或使用單一入口分發模式。