Struts2 官方教程之Struts Tags(六)——Generic Tags(Control Tags )

来源:互联网 发布:java安装教程详细 编辑:程序博客网 时间:2024/04/29 10:49

开头要说的:在早期的应用开发中,表现层Jsp页面主要使用Jsp脚本来控制输出。这样,在Jsp中嵌套了java脚本,这种方式不管是可读性还是可维护性都很差,几乎使Jsp成为Java的子集。从Jsp1.1之后,才增加了Jsp标签库,这种情况才有所好转。

Generic tags are used for controlling the execution flow when the Jsppages render. These tags also allow for data extraction from places other than your action or the value stack, such asLocalization, JavaBeans, and including aditional URLs or action executions.

Generic tags用于控制显示,这些标签也可以从一些地方提取数据,但与action或者值栈不同,比如从Localization, JavaBeans以及url传递过来的值。

  • Control Tags provide control flow, such as if, else, and iterator.
  • Data Tags allow for data manipulation or creation, such as bean, push, and i18n.

Control Tags

  • if
  • elseif
  • else
  • append
  • generator
  • iterator
  • merge
  • sort
  • subset
Data Tags
  • a
  • action
  • bean
  • date
  • debug
  • i18n
  • include
  • param
  • property
  • push
  • set
  • text
  • url

Examples

<s:if test="%{false}">    <div>Will Not Be Executed</div></s:if><s:elseif test="%{true}">    <div>Will Be Executed</div></s:elseif><s:else>    <div>Will Not Be Executed</div></s:else>


 

append标签:

Component for AppendIteratorTag, which jobs is to append iterators to form an appended iterator whereby entries goes from one iterator to another after each respective iterator is exhausted of entries.

用于将多个集合对象拼接起来,组成一个新的集合,通过这种拼接,从而允许通过<s:iterator../>就完成对多个集合的迭代。

Name

Required

Default

Evaluated

Type

Description

idfalse falseStringDeprecated. Use 'var' insteadvarfalse falseStringThe name of which if supplied will have the resultant appended iterator stored under in the stack's context

有两个属性,但是var替代了id, 不赞成使用id属性 ,<s:append >可以包含多个<s:param>,每个<s:param>指定一个集合。

public class AppendIteratorTagAction extends ActionSupport { private List myList1; private List myList2; private List myList3; public String execute() throws Exception {     myList1 = new ArrayList();     myList1.add("1");     myList1.add("2");     myList1.add("3");     myList2 = new ArrayList();     myList2.add("a");     myList2.add("b");     myList2.add("c");     myList3 = new ArrayList();     myList3.add("A");     myList3.add("B");     myList3.add("C");     return "done"; } public List getMyList1() { return myList1; } public List getMyList2() { return myList2; } public List getMyList3() { return myList3; }
<s:append var="myAppendIterator">     <s:param value="%{myList1}" />     <s:param value="%{myList2}" />     <s:param value="%{myList3}" /></s:append><s:iterator value="%{#myAppendIterator}">     <s:property /></s:iterator>


 

generator

Description

NOTE: JSP-TAG

Generate an iterator based on the val attribute supplied.

NOTE: The generated iterator will ALWAYS be pushed into the top of the stack, and poped at the end of the tag.

generator标签可以将指定字符串按指定分隔符分隔成多个子串,临时生成的多个字串可以使用iterator标签来迭代输出。可以理解成:generator将一个字符串转化成一个List集合,在这标签体内,整个临时生成的集合将位于ValueStack的顶端,但一旦该标签结束,该集合将被移出。

Parameters

Dynamic Attributes Allowed:

false 

Name

Required

Default

Evaluated

Type

Description

converterfalse falseorg.apache.struts2.util.IteratorGenerator.ConverterThe converter to convert the String entry parsed fromval into an object将字符串转化成对象countfalse falseIntegerThe max number entries to be in the iterator集合中元素的总数idfalse falseStringDeprecated. Use 'var' insteadseparatortrue falseStringThe separator to be used in separating the val into entries of the iterator指定用于解析字符串的分隔符valtrue falseStringThe source to be parsed into an iterator指定被解析的字符串varfalse falseStringThe name to store the resultant iterator into page context, if such name is supplied如何使用该属性,将把生成的iterator对象放入stackContext中

Examples

Example One:<pre>Generate a simple iterator<s:generator val="%{'aaa,bbb,ccc,ddd,eee'}"> <s:iterator>     <s:property /><br/> </s:iterator></s:generator></pre>This generates an iterator and print it out using the iterator tag.Example Two:<pre>Generate an iterator with count attribute<s:generator val="%{'aaa,bbb,ccc,ddd,eee'}" count="3"> <s:iterator>     <s:property /><br/> </s:iterator></s:generator></pre>This generates an iterator, but only 3 entries will be available in the iteratorgenerated, namely aaa, bbb and ccc respectively because count attribute is set to 3Example Three:<pre>Generate an iterator with var attribute<s:generator val="%{'aaa,bbb,ccc,ddd,eee'}" count="4" separator="," var="myAtt" /><% Iterator i = (Iterator) pageContext.getAttribute("myAtt"); while(i.hasNext()) {     String s = (String) i.next(); %>     <%=s%> <br/><%    }%></pre>This generates an iterator and put it in the PageContext under the key as specifiedby the var attribute.Example Four:<pre>Generate an iterator with comparator attribute<s:generator val="%{'aaa,bbb,ccc,ddd,eee'}" converter="%{myConverter}"> <s:iterator>     <s:property /><br/> </s:iterator></s:generator>public class GeneratorTagAction extends ActionSupport {  ....  public Converter getMyConverter() {     return new Converter() {         public Object convert(String value) throws Exception {             return "converter-"+value;         }     };  }  ...}</pre>This will generate an iterator with each entries decided by the converter supplied. Withthis converter, it simply add "converter-" to each entries.


 

iterator

Description

Iterator will iterate over a value. An iterable value can be any of: java.util.Collection, java.util.Iterator,

Parameters

Dynamic Attributes Allowed:

false 

Name

Required

Default

Evaluated

Type

Description

beginfalse0falseIntegerif specified the iteration will start on that indexendfalseSize of the 'values' List or array, or 0 if 'step' is negativefalseIntegerif specified the iteration will end on that index(inclusive)idfalse falseStringDeprecated. Use 'var' insteadstatusfalsefalsefalseBooleanIf specified, an instanceof IteratorStatus will be pushed into stack upon each iterationstepfalse1falseIntegerif specified the iteration index will be increased by this value on each iteration. It can be a negative value, in which case 'begin' must be greater than 'end'valuefalse falseStringthe iteratable source to iterate over, else an the object itself will be put into a newly created Listvarfalse falseStringName used to reference the value pushed into the Value Stack

Examples

The following example retrieves the value of the getDays() method of the current object on the value stack and uses it to iterate over.The <s:property/> tag prints out the current value of the iterator.

<s:iterator value="days">  <p>day is: <s:property/></p></s:iterator>


 

The following example uses a Bean tag and places it into the ActionContext. The iterator tag will retrieve that object from the ActionContext and then calls its getDays() method as above. The status attribute is also used to create an IteratorStatus object, which in this example, its odd() method is used to alternate row colours:

<s:bean name="org.apache.struts2.example.IteratorExample" var="it">  <s:param name="day" value="'foo'"/>  <s:param name="day" value="'bar'"/></s:bean><p/><table border="0" cellspacing="0" cellpadding="1"><tr>  <th>Days of the week</th></tr><p/><s:iterator value="#it.days" status="rowstatus">  <tr>    <s:if test="#rowstatus.odd == true">      <td style="background: grey"><s:property/></td>    </s:if>    <s:else>      <td><s:property/></td>    </s:else>  </tr></s:iterator></table>


 

The next example will further demonstrate the use of the status attribute, using a DAO obtained from the action class through OGNL, iterating over groups and their users (in a security context). The last() method indicates if the current object is the last available in the iteration, and if not, we need to separate the users using a comma:

<s:iterator value="groupDao.groups" status="groupStatus">     <tr class="<s:if test="#groupStatus.odd == true ">odd</s:if><s:else>even</s:else>">         <td><s:property value="name" /></td>         <td><s:property value="description" /></td>         <td>             <s:iterator value="users" status="userStatus">                 <s:property value="fullName" /><s:if test="!#userStatus.last">,</s:if>             </s:iterator>         </td>     </tr> </s:iterator>


The next example iterates over a an action collection and passes every iterator value to another action. The trick here lies in the use of the '[0]' operator. It takes the current iterator value and passes it on to the edit action. Using the '[0]' operator has the same effect as using <s:property />. (The latter, however, does not work from inside the param tag).

<s:action name="entries" var="entries"/>     <s:iterator value="#entries.entries" >         <s:property value="name" />         <s:property />         <s:push value="...">             <s:action name="edit" var="edit" >                 <s:param name="entry" value="[0]" />             </s:action>         </push>     </s:iterator>


A loop that iterates 5 times

<s:iterator var="counter" begin="1" end="5" >   <!-- current iteration value (1, ... 5) -->   <s:property value="top" /></s:iterator>


Another way to create a simple loop, similar to JSTL's <c:forEach begin="..." end="..." ...> is to use some OGNL magic, which provides some under-the-covers magic to make 0-n loops trivial. This example also loops five times.

<s:iterator status="stat" value="(5).{ #this }" >   <s:property value="#stat.count" /> <!-- Note that "count" is 1-based, "index" is 0-based. --></s:iterator>


A loop that iterates over a partial list

<s:iterator value="{1,2,3,4,5}" begin="2" end="4" >   <!-- current iteration value (2,3,4) -->   <s:property value="top" /></s:iterator>


 

merge
Edit Page   Browse Space  Add Page   Add News
Please make sure you have read the Tag Syntax document and understand how tag attribute syntax works.

Description

Component for MergeIteratorTag, which job is to merge iterators and successive call to the merged iterator will cause each merge iterator to have a chance to expose its element, subsequently next call will allow the next iterator to expose its element. Once the last iterator is done exposing its element, the first iterator is allowed to do so again (unless it is exhausted of entries).

Internally the task are delegated to MergeIteratorFilter

Example if there are 3 lists being merged, each list have 3 entries, the following will be the logic.

merge写append很相似,区别在于集合的顺序不同。左边是merge右边是append,相信一目了然

  1. Display first element of the first list                                      Displayfirstelement of the first list    
  2. Display first element of the second list                               Display first element of the first list                     
  3. Display first element of the third list                                     Display first element of the first list        
  4. Display second element of the first list
  5. Display second element of the second list
  6. Display second element of the third list
  7. Display third element of the first list
  8. Display thrid element of the second list
  9. Display third element of the thrid list

Parameters

Dynamic Attributes Allowed:

false 

Name

Required

Default

Evaluated

Type

Description

idfalse falseStringDeprecated. Use 'var' insteadvarfalse falseStringThe name where the resultant merged iterator will be stored in the stack's context

Examples

 

public class MergeIteratorTagAction extends ActionSupport { private List myList1; private List myList2; private List myList3; public List getMyList1() {     return myList1; } public List getMyList2() {     return myList2; } public List getMyList3() {     return myList3; } public String execute() throws Exception {     myList1 = new ArrayList();     myList1.add("1");     myList1.add("2");     myList1.add("3");     myList2 = new ArrayList();     myList2.add("a");     myList2.add("b");     myList2.add("c");     myList3 = new ArrayList();     myList3.add("A");     myList3.add("B");     myList3.add("C");     return "done"; }}

<s:merge var="myMergedIterator1">     <s:param value="%{myList1}" />     <s:param value="%{myList2}" />     <s:param value="%{myList3}" /></s:merge><s:iterator value="%{#myMergedIterator1}">     <s:property /></s:iterator>

sort
 
Please make sure you have read the Tag Syntax document and understand how tag attribute syntax works.

Description

NOTE: JSP-TAG

A Tag that sorts a List using a Comparator both passed in as the tag attribute. If 'var' attribute is specified, the sorted list will be placed into the PageContext attribute using the key specified by 'var'. The sorted list will ALWAYS be pushed into the stack and poped at the end of this tag.

该标签用于对指定集合元素进行排序,必须提供自己的排序规则,要实现自己的Comparator,需要实现java.util.Comparator接口

Parameters

Dynamic Attributes Allowed:

false 

Name

Required

Default

Evaluated

Type

Description

comparatortrue falsejava.util.ComparatorThe comparator to useidfalse falseStringDeprecated. Use 'var' insteadsourcefalse falseStringThe iterable source to sort指定被排序的集合,不指定,则对ValueStack栈顶的集合进行排序。varfalse falseString

The name to store the resultant iterator into page context, if such name is supplied

指定该属性,则将生成的Iterator对象设置成page范围的属性。

Examples

USAGE 1:<s:sort comparator="myComparator" source="myList">     <s:iterator>     <!-- do something with each sorted elements -->     <s:property value="..." />     </s:iterator></s:sort>USAGE 2:<s:sort var="mySortedList" comparator="myComparator" source="myList" /><%   Iterator sortedIterator = (Iterator) pageContext.getAttribute("mySortedList");   for (Iterator i = sortedIterator; i.hasNext(); ) {     // do something with each of the sorted elements   }%>


 

subset
 

Description

NOTE: JSP-TAG

A tag that takes an iterator and outputs a subset of it. It delegates to org.apache.struts2.util.SubsetIteratorFilter internally to perform the subset functionality.

用于取得集合的子集。底层通过org.apache.struts2.util.SubsetIteratorFilter来实现

Parameters

Dynamic Attributes Allowed:

false 

Name

Required

Default

Evaluated

Type

Description

countfalse falseInteger

Indicate the number of entries to be in the resulting subset iterator

子集元素个数。

deciderfalse falseorg.apache.struts2.util.SubsetIteratorFilter.DeciderExtension to plug-in a decider to determine if that particular entry is to be included in the resulting subset iteratoridfalse falseStringDeprecated. Use 'var' insteadsourcefalse falseStringIndicate the source of which the resulting subset iterator is to be derived base onstartfalse falseIntegerIndicate the starting index (eg. first entry is 0) of entries in the source to be available as the first entry in the resulting subset iterator由开发都自己指定是否选择选中该元素varfalse falseStringThe name to store the resultant iterator into page context, if such name is supplied

Examples

public class MySubsetTagAction extends ActionSupport {     public String execute() throws Exception {        l = new ArrayList();        l.add(new Integer(1));        l.add(new Integer(2));        l.add(new Integer(3));        l.add(new Integer(4));        l.add(new Integer(5));        return "done";     }     public Integer[] getMyArray() {        return a;     }     public List getMyList() {        return l;      }     public Decider getMyDecider() {     return new Decider() {         public boolean decide(Object element) throws Exception {             int i = ((Integer)element).intValue();             return (((i % 2) == 0)?true:false);         }     };     } }


 

<!-- s: List basic -->   <s:subset source="myList">      <s:iterator>         <s:property />      </s:iterator>   </s:subset>


 

<!-- B: List with count -->   <s:subset source="myList" count="3">      <s:iterator>          <s:property />      </s:iterator>    </s:subset>


 

<!--  C: List with start -->     <s:subset source="myList" count="13" start="3">        <s:iterator>          <s:property />        </s:iterator>     </s:subset>


 

<!--  D: List with var -->     <s:subset var="mySubset" source="myList" count="13" start="3" />     <%         Iterator i = (Iterator) pageContext.getAttribute("mySubset");         while(i.hasNext()) {     %>     <%=i.next() %>     <%  } %>


 

<!--  D: List with Decider -->    <s:subset source="myList" decider="myDecider">           <s:iterator>                <s:property />           </s:iterator>    </s:subset>


 

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 父母看孩子总是吵架怎么办 20岁父母离婚我怎么办 碰到没素质的人怎么办 父母抛弃了我该怎么办 父母说家里没钱困难怎么办 遇到素质低的老婆怎么办 孩子考试心里素质差怎么办 5岁儿童脾气不好怎么办 有一个素质差的父母怎么办 孩子对什么都无所谓怎么办 孩子在学习上无所谓怎么办 孩子对学习无所谓的态度怎么办 孩子不上进什么都无所谓怎么办 倔强的学生不理老师怎么办 一岁宝宝特别犟怎么办 孩子遇到问题喜欢发脾气怎么办 企业培养新人跑了怎么办 二年级学生读不懂题目怎么办 6岁宝宝有鼻炎怎么办 外地儿童怎么办北京医保卡 江苏联宝投资的钱怎么办 银行叫开了证券怎么办 中班心理健康我不开心了怎么办 大学生心理健康课总是抢不到怎么办 孩子成绩提不上去怎么办 孩子数学不开窍怎么办 二年级 初中孩子语文不开窍怎么办 分到的班级都是差生怎么办 初三了英语差怎么办呀 初三了英语差的很怎么办 五年级英语太差怎么办 听课效率没有自学效率高怎么办 小学生不好好写作业怎么办 带的家教成绩没有提高怎么办 学生出国学校成绩证明怎么办 学生成绩考差了班主任怎么办 高一的学生成绩跟不上怎么办 综合素质评价手册丢了怎么办 小学综合素质评价手册丢了怎么办 人体质不出汗差怎么办 儿子一年级语文成绩太差怎么办