Struts2 <s:if>, <s:elseif>, <s:else>標籤示例用於執行基本的條件檢查。這裏創建一個Web工程:strut2iftag,來演示在多個複選框如何設置的默認值,整個專案的結構如下圖所示:
<s:if> 標籤可以單獨使用。
<s:if test="%{#variable=='String 1'}">
This is String 1
</s:if>
或使用 <s:elseif> 標籤
<s:if test="%{#variable=='String 1'}">
This is String 1
</s:if>
<s:elseif test="%{#variable=='String 2'}">
This is String 2
</s:elseif>
和/或單/多<s:else>標籤。
<s:if test="%{#variable=='String 1'}">
This is String 1
</s:if>
<s:elseif test="%{#variable=='String 2'}">
This is String 2
</s:elseif>
<s:else>
Other Strings
</s:else>
以上所有的陳述是正確的。讓我們看一個例子來說明使用 Struts2 的“If, elseIf 和 else" 標籤。
1. 動作
一個Action類的字串屬性,其中包含了“Struts 2”的值。
IfTagAction
package com.xuhuhu.common.action;
import com.opensymphony.xwork2.ActionSupport;
public class IfTagAction extends ActionSupport{
private String framework = "Struts 2";
public String getFramework() {
return framework;
}
public void setFramework(String framework) {
this.framework = framework;
}
public String execute() {
return SUCCESS;
}
}
2. If, elseIf 和 else 標籤示例
JSP頁面來顯示使用 if, elseif 和 else 標籤的執行檢查“framework”變數。
if.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body>
<h1>Struts 2 If, Else, ElseIf tag example</h1>
<s:set name="webFramework" value="framework"/>
<s:if test="%{#webFramework=='Struts 2'}">
This is Struts 2
</s:if>
<s:elseif test="%{#webFramework=='Struts 1'}">
This is Struts 1
</s:elseif>
<s:else>
Other framework
</s:else>
</body>
</html>
3. struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="ifTagAction" class="com.xuhuhu.common.action.IfTagAction" > <result name="success">pages/if.jsp</result> </action> </package> </struts>
4. 示例
http://localhost:8080/struts2iftag/ifTagAction.action

