首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Struts2 if/elseif/else 標籤條件判斷完整指南

     編輯:Java 相關知識

標籤語法

<s:if test="%{condition1}">...</s:if>
<s:elseif test="%{condition2}">...</s:elseif>
<s:else>...</s:else>

單獨使用或組合使用,邏輯同 Java if-else if-else。

完整示例

Action

public class HelloWorldAction {
    private String name;
    public String execute() { return "success"; }
    // getter/setter
}

index.jsp - 表單提交

<form action="hello">
    <select name="name">
        <option>Mike</option>
        <option>Jason</option>
        <option>Mark</option>
    </select>
    <input type="submit" value="Say Hello"/>
</form>

HelloWorld.jsp - 條件顯示

<s:if test="name=='Mike'">
    You have selected 'Mike'.
</s:if>
<s:elseif test="name=='Jason'">
    You have selected 'Jason'
</s:elseif>
<s:else>
    You have not selected 'Mike' or 'Jason'.
</s:else>

struts.xml

<action name="hello" class="com.yiibai.struts2.HelloWorldAction" method="execute">
    <result name="success">/HelloWorld.jsp</result>
</action>

運行效果

  • 選 Mike → 顯示 "You have selected 'Mike'."
  • 選 Jason → 顯示 "You have selected 'Jason'"
  • 選 Mark → 顯示 "You have not selected 'Mike' or 'Jason'."

進階用法

  • test 可用 OGNL 表達式:user.age > 18、list.size() > 0。
  • 可嵌套其他標籤(<s:iterator>、<s:property> 等)。

總結

if/elseif/else 標籤將條件邏輯移至視圖層,保持 Action 純粹,是 Struts2 表現層邏輯控制的核心工具。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved