Struts2 <s:subset >標籤用來輸出一個iterator元素的子集或部分。在本教學中,將建立一個「數位」列表中,包含了10個元素(從 1 - 10), 並使用<s:subset >標記 「start & count」 屬性和判定方法,以輸出一個疊代(列表)的子集。這裡建立一個Web工程:struts2subsettag,來演示在多個核取方塊如何設定的預設值,整個專案的結構如下圖所示:
SubsetTagAction.java
package com.tw511.common.action; import java.util.ArrayList; import java.util.List; import org.apache.struts2.util.SubsetIteratorFilter.Decider; import com.opensymphony.xwork2.ActionSupport; public class SubsetTagAction extends ActionSupport{ private List<String> numbers = new ArrayList<String>(); public String execute() { numbers.add("Number 1"); numbers.add("Number 2"); numbers.add("Number 3"); numbers.add("Number 4"); numbers.add("Number 5"); numbers.add("Number 6"); numbers.add("Number 7"); numbers.add("Number 8"); numbers.add("Number 9"); numbers.add("Number 10"); return SUCCESS; } public List<String> getNumbers() { return numbers; } public void setNumbers(List<String> numbers) { this.numbers = numbers; } public Decider getNumberDecider() { return new Decider() { public boolean decide(Object obj) throws Exception { String number = ((String)obj).toString(); if(("Number 7").equals(number)){ return true;//display it }else{ return false;//ignore } } }; } }
subset.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head><title>Struts2 subset標籤範例 - www.tw511.com</title> </head> <body> <h1>Struts 2 Subset tag example</h1> <table border="1px" cellpadding="8px"> <tr valign="top"> <td> 1. Display all numbers. <ol> <s:subset source="numbers"> <s:iterator> <li><s:property /></li> </s:iterator> </s:subset> </ol> </td> <td> 2. Display numbers , from #2 to #6 <ol> <s:subset source="numbers" start="1" count="5"> <s:iterator> <li><s:property /></li> </s:iterator> </s:subset> </ol> </td> <td> 3. Display numbers 7 only, with decider <ol> <s:subset source="numbers" decider="numberDecider"> <s:iterator> <li><s:property /></li> </s:iterator> </s:subset> </ol> </td> </tr> </table> </body> </html>
<?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="subsetTagAction" class="com.tw511.common.action.SubsetTagAction" > <result name="success">/pages/subset.jsp</result> </action> </package> </struts>
http://localhost:8080/struts2subsettag/subsetTagAction.action
在瀏覽器中輸出以上網址存取,顯示如下結果: