Struts2 <s:subset>標簽示例
Struts2 <s:subset >標簽用來輸出一個iterator元素的子集或部分。在本教學中,將創建一個“數字”列表中,包含了10個元素(從 1 - 10), 並使用<s:subset >標記 “start & count” 屬性和判定方法,以輸出一個迭代(列表)的子集。這裡創建一個Web工程:struts2subsettag,來演示在多個複選框如何設置的默認值,整個項目的結構如下圖所示:
1. 動作 - Action
Action類填充元素到一個列表,以及一個判定方法進行篩選,以顯示元素。
如果判定方法返回一個“true”是指顯示該值; 否則,忽略它。可以在這裡實現過濾器的邏輯。
SubsetTagAction.java
package com.gitbook.netmon.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 } } }; } }
2. <s:subset>標簽示例
JSP頁麵使用<s:subset>標簽迭代器輸出一個子集。
“start”以及“count”在<s:subset>標簽屬性是從0開始,這意味著 <s:subset source=”numbers” start=”1″ count=”5″> 將提取元素 #2 到 #6.
subset.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head><title>Struts2 subset標簽示例 - www.gitbook.net</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>
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="subsetTagAction" class="com.gitbook.netmon.action.SubsetTagAction" > <result name="success">/pages/subset.jsp</result> </action> </package> </struts>
4. 示例
http://localhost:8080/struts2subsettag/subsetTagAction.action
在瀏覽器中輸出以上網址訪問,顯示如下結果:
參考