self_sumary_s2_tag

11 篇文章 0 订阅

 The id attribute is deprecated in Struts 2.1.x, and has been replaced by the var attribute.
s:hidden 标签不要用,建议用HTML的<input type="hidden" id="xxx" name="xxx" value="${xxx}"/>   <!--jstl方式方的值-->

Tag标签属性注意点之一:

 Tag属性遵循下面三条规则:

  1. 所有的String属性类型,都会被符号 "%{ ... }"解析,例如:
<s:textfield key="state.label" name="state" value="ca"/></span>
上面这个可能会产生错误,由于value属性不是一个String类型,那么传递给value的都会当成一个表达式而非字符串文本。原因是:如果给textfield的value属性传递一个字符串"ca",那么框架会寻找一个方法getCa.</span>

传递一个字符串给value属性的正确方法一:利用解析符号

<s:textfield key="state.label" name="state" value="%{'ca'}" />

方法二:<code>value="'ca'"</code></span>


2.所有non-String attribute 将不会被解析。如果使用上述解析符号,则相当于把解析符号去掉。

例如:

<span style="font-size:14px;"><s:select key="state.label" name="state" multiple="true"/></span>
由于,属性  multiple 是映射到boolean类型的,所以,框架不会将“true”解释为String,而是看作一个表达式,并自动转化为boolean类型。


如果这样呢?

<span style="font-size:14px;"><s:select key="state.label" name="state" multiple="%{true}"/></span>
结果是:不会被解析,自动转为为boolean类型,和上面效果一样。


                                          表达式语言符号
<p>Username: ${user.username}</p>A JavaBean object in a standard context in Freemarker, Velocity, or JSTL EL (Not OGNL).
<s:textfield name="username"/>A username property on the Value Stack.(struts2值栈上会存放属性的值)
<s:url id="es" action="Hello">
   <s:param name="request_locale">
     es
   </s:param>
</s:url>
<s:a href="%{es}">Espanol</s:a>
Another way to refer to a property placed on the Value Stack.
<s:property
   value="#session.user.username" />
The username property of the User object in the Session context.
<s:select
   label="FooBar" name="foo"
   list="#{&# 39 ;username&# 39 ;:&# 39 ;trillian&# 39 ;,
     &# 39 ;username&# 39 ;:&# 39 ;zaphod&# 39 ;}" />
A static Map, as in put("username","trillian").

注:

1、“#”符号有三种用途:   

(1)、访问非根对象(struts中值栈为根对象)如OGNL上下文和Action上下文,#相当于ActionContext.getContext();下表有几个ActionContext中有用的属性:   

    parameters   
     包含当前HTTP请求参数的Map   
     #parameters.id[0]作用相当于request.getParameter("id")    
        
    request   
     包含当前HttpServletRequest的属性(attribute)的Map   
     #request.userName相当于request.getAttribute("userName")    
        
    session   
     包含当前HttpSession的属性(attribute)的Map   
     #session.userName相当于session.getAttribute("userName")    
        
    application   
     包含当前应用的ServletContext的属性(attribute)的Map   
     #application.userName相当于application.getAttribute("userName")    
        
      
    注:attr 用于按request > session > application顺序访问其属性(attribute),#attr.userName相当于按顺序在以上三个范围(scope)内读取userName属性,直到找到为止。用于过滤和投影(projecting)集合,如books.{?#this.price<100};构造Map,如#{'foo1':'bar1', 'foo2':'bar2'}。   
      
        
      
    (2)、用于过滤和投影(projecting)集合,如: books.{?#this.price>35}     
      
    books.{?#this.price>35}   
      
    (3)、构造Map,如: #{'foo1':'bar1', 'foo2':'bar2'}     
      
    #{'foo1':'bar1', 'foo2':'bar2'}这种方式常用在给radio或select、checkbox等标签赋值上。如果要在页面中取一个map的值可以这样写:    
      
    <s:property value="#myMap['foo1']"/>     
      
    <s:property value="#myMap['foo1']"/>   
<span style="background-color: rgb(255, 204, 153);"><span style="font-size:18px;">
</span></span>


从上下文环境中获取值的方法:

The following are ways to obtain Application scope attributes, Session scope attributes, Request scope attributes, Request parameters and framework Context scope parameters:-
Application Scope Attribute

Assuming there's an attribute with name 'myApplicationAttribute' in the Application scope.
<s:property value="%{#application.myApplicationAttribute}" />
Session Scope Attribute

Assuming there's an attribute with name 'mySessionAttribute' in the Session scope.
<s:property value="%{#session.mySessionAttribute}" />
Request Scope Attribute

Assuming there's an attribute with name 'myRequestAttribute' in the Request scope.
<s:property value="%{#request.myRequestAttribute}" />
Request Parameter

Assuming there's a request parameter myParameter (e.g. http://host/myApp/myAction.action?myParameter=one).
<s:property value="%{#parameters.myParameter}" />
Context Scope Parameter

Assuming there's a parameter with the name myContextParam in our context.  --这个相当于间接的获取了struts value stack中的该名称对应的值。应该只有property标签会这么使用
<s:property value="%{#myContextParam}" />                                      



Control Tags(控制类标签)

1. <s:if>标签的用途之一:

通过判断动态在jsp页面动态部署标签元素(js中也可以实现,不过是响应页面事件;而jsp利用<s:if>标签是通过后台传到值栈的数据做出响应)

例子:

<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>
详细例子:

    <s:if test='"1" == #rqlx'>
       <div><input name="xsrq"/><span class="code-tag"></div></span> </s:if> <s:if test='"2" == #rqlx'> 
       <div> <input name="xsrq"/><pre class="code-xml"><span class="code-tag"></div>
    </s:if>

 
 
 

2. <s:append>

作用:将几个集合放在一起进行迭代

例子:

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 />    <!--表示打印输出当前value值-->
</s:iterator>

输出:

1

2

3

a

b

c

A

B

C

该标签属性:

Name
Required
Default
Evaluated
Type
Description
idfalse falseStringDeprecated. Use 'var' instead
varfalse falseStringThe name of which if supplied will have the resultant appended iterator stored under in the stack's context


3. <s:iterator>


属性说明:

Name
Required
Default
Evaluated
Type
Description
idfalse falseStringDeprecated. Use 'var' instead
statusfalsefalsefalseBooleanIf specified, an instanceof IteratorStatus will be pushed into stack upon each iteration
valuefalse falseStringthe iteratable source to iterate over, else an the object itself will be put into a newly created List
varfalse falseStringName used to reference the value pushed into the Value Stack

作用:迭代

value="days"将会使能获取当前存在值栈上的对象的getDays()方法获得的值!

<s:iterator value="days">
  <p>day is: <s:property/></p>  <!--输出当前的value的值-->
</s:iterator>


例子:循环5次

<s:iterator status="stat" value="{1,2,3,4,5}" >
   <!-- grab the index (start with 0 ... ) -->
   <s:property value="#stat.index" />

   <!-- grab the top of the stack which should be the -->
   <!-- current iteration value (1, ... 5) -->
   <s:property value="top" />
</s:iterator>



利用s:iterator标签简单循环的另一种方式,和JSTL的<c:forEach begin="..." end="..." ...>的类似,下面也是循环5次~

<s:iterator status="stat" value="(5).{ #this }" >
   <s:property value="#stat.count" /> <!-- Note that "count"是从1开始计算, "index" 是从0开始计算. -->
</s:iterator>                          
<!--s:property标签的作用就是输出当前value的值 -->

例子:遍历map
value可以直接定义为:
value="#{"1":"a","2":"b"}"

每个元素以都好隔开。元素之间的key和value 冒号隔开
value 也可以是数据栈里面的java.util.Map对象
遍历写法如下:

Java代码   收藏代码
<s:iterator value="map" id="id" status="st">  
    key : <s:property value='key'/>  
    value:<s:property vlaue='value'/>  
</s:iterator>  


S:iterator的标签的属性扩展

在说明s:iterator标签的使用前,先了解下struts2中的Value Stack。这里参考了webwork中对Value Stack的描述,由于struts2是在webwork的基础上进行升级的,因此webwork对于Value Stack的表述同样适用于struts2。在这里不描述Value Stack具体做什么,但有两点需要注意:

  1.  一个value stack本质上是一个List;
  2. 在栈中调用[n]将返回一个从位置n开始的子栈;

对于2举个例子说明。假定Value Stack包含了[model,action,others],那么

  1. [0] --- 返回 [model,action,others];
  2. [1] --- 返回 [action,others];
  3. [2] --- 返回 [others];

现在将开始介绍s:iterator的一些使用。以下代码片段均在开发环境eclipse3.4 wtp、tomcat5.5、jdk5上使用struts2.1.6测试通过。

1)、访问 days

defined  List<String>  days   ["Monday","Thursday","Friday","Sunday"]

    <s:iterator value="days"><s:property /></s:iterator>

2)、使用top关键字使用(过滤掉Monday)

defined  List<String>  days   ["Monday","Thursday","Friday","Sunday"]

    <s:iterator value="days">  
                <s:if test="top!='Monday'">  
                    <s:property />  
                </s:if>  
            </s:iterator>  

  • top 指代当前迭代元素,可以为对象;
  • 这里的top可用[0].top替代,但不能使用[0]。[0]代表整个栈对象。如果单纯调用[0]将会调用其toString()方法输出对象信息;

3)、使用 last / first关键字(属于status)

defined  String[][] aTs = { { "一", "二", "三", "四" },{ "一一", "二二", "三三", "四四"} };

    <!--遍历二维数组,The trick here is to use 'top' as the value for the inner iterator-->  
              <s:iterator value="aTs" status="of">  
              <s:if test="#of.last"><br/></s:if>  
              <s:iterator value="top">  
    <!--亦可用[0].top替代。如果单纯用[0],则会同时打印该处栈对象信息-->  
             <s:property />  
              </s:iterator>  
              </s:iterator>  

  • iterator 标签中的status属性代表当前迭代的位置;
  • #of.last用于判断当前迭代到的元素是否为最后一个元素;
  • last返回一个boolean类型;
  • first返回一个boolean类型;

4)、使用 odd/ even关键字(属于status)

下面的例子要实现每行输出颜色不同的效果。

defined  List<String>  days   ["Monday","Thursday","Friday","Sunday"]

           <!--奇数行显示为红色,偶数行显示为绿色-->  
           <s:iterator value="days" status="offset">  
        <s:else>  
            <s:if test="#offset.odd==true">  
                <li style="color: red" mce_style="color: red"><s:property /></li>  
            </s:if>  
            <s:else>  
                <li><s:property /></li>  
            </s:else>  
        </s:else>  
    </s:iterator>  

  • odd关键字用来判断当前迭代位置是否为奇数行。odd返回boolean类型;
  • even关键字用来判断当前迭代位置是否为偶数行。even返回boolean类型

5)、总结下,当声明iterator的status属性时,类似上面的例子,可以通过#statusName.method使用以下方法:

  • even : boolean - 如果当前迭代位置是偶数返回true
  • odd : boolean - 如果当前迭代位置是奇数返回true
  • count : int - 返回当前迭代位置的计数(从1开始)
  • index : int - 返回当前迭代位置的编号(从0开始)
  • first : boolean - 如果当前迭代位置是第一位时返回true
  • last : boolean - 如果当前迭代位置是最后一位时返回true
  • modulus(operand : int) : int - 返回当前计数(从1开始)与指定操作数的模数

6)、最后再来看下在iterator中调用value stack的用法。

假定countries是一个List对象,每一个country有一个name属性和一个citys List对象,并且每一个city也有一个name属性。

那么我们想要在迭代 citys 时访问所属country的name属性就的用如下方式:

([0]代表的最内层的位于值栈上的对象- -这里是city对象,[1]代表的是次外层的对象- -这里是country)

    <s:iterator value="countries">  
        <s:iterator value="cities">  
            <s:property value="name"/>, <s:property value="[1].name"/><br>  
        </s:iterator>  
    </s:iterator>  

  • 这里的 <s:property value="name"/>取的是ctiy.name;<s:property value="[1].name"/>取得是country.name
  • <s:property value="[1].name"/> 等价于 <s:property value="[1].top.name"/>
  • we refer to a specific position on the stack: '[1]'.
  • The top of the stack, position 0, contains the current city, pushed on by the inner iterator;
  •  position 1 contains the current country, pushed there by the outer iterator.(city处于当前栈,即top或者[0],而[1]指明了外层iterator对象,即country)
 '[n]'标记引用开始位置为n的子栈(sub-stack),而不仅仅是位置n处的对象。因此'[0]'代表整个栈,而'[1]'是除top对象外所有的栈元素


后台获取到的list,进行迭代:

 <s:iterator value="categoryAction.categories" var="c">

<s:property value="#c.title" />

<s:property value="#c.description" />

<br />

</s:iterator> 


jsp中定义List对象,将其放入request范围内后,方可在s:iterator标签中使用!(这是一种利用jsp中对象的方法)

<%
 List<Category> categories=categoryAction.getCategories();
System.out.println(categories.get(1).getDescription()); //这里显示了categories里是有值的
request.setAttribute("categories",categories);
%>
<s:iterator value="#request.categories" var="c">
	    <s:property value="#c.title" /> |
    <s:property value="#c.description" /> 
		    <br />
	</s:iterator>
追问
成功了,谢谢!我想问下为什么要放到request中?request是干什么的?
回答
request是一次请求范围,放在request里的值在一次请求过程中是可以获取到值的。记得给分哈!
提问者评价
谢谢~!


5.<s:generator>标签

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

参数

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' instead
separatortrue 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

例子

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 iterator
generated, namely aaa, bbb and ccc respectively because count attribute is set to 3

Example 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 specified
by 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. With
this converter, it simply add "converter-" to each entries.


generator标签使用情形例子

有的时候,我们在数据库中,会在一个字段存放多个值,之间用特殊字符分割。
比如,需要某个字段存放了用户个人使用的编程语言(可以多选)
1 .Java
2 .C
3 .PHP
如果用户选择了 1 2 ,那么,在数据库中的 "编程语言" 一栏里,可能会写入 "1,2" (此处以逗号分隔).
 
当在查询页面需要显示编程语言时,我们不能直接显示 "1,2" ,而是需要转换成 "Java、C"
方案 1 :我们可以在后台得到查询结果后转义,这个需要在后台遍历查询的结果集,效率不高。
方案 2 :我们可以使用struts2的标签<s:generator>实现上面的功能
 
<s:generator val="languageItem" separator="," converter="%{languageItemConverter}">
    <s:iterator status="row_languageItem">
        <s:if test="#row_languageItem.index != 0">
            、<s:property />
        </s:if>
        <s:else>
            <s:property />
        </s:else>
    </s:iterator>
</s:generator>



val= "languageItem" :为后台保存 "1,2" 的变量;
separator= "," :标明变量的分隔符;
converter= "%{languageItemConverter}" :指明languageItem的转换方法,我们需要在对应的Action中添加方法 public org.apache.struts2.util.IteratorGenerator.Converter getLanguageItemConverter(){}。
 
<s:generator>内部需要嵌套使用<s:iterator>来遍历后台转换后产生的结果集,然后使用特定的方式显示(例子中是通过 "、" 来分隔显示转义后的字符)。
 
下面是此方法Action的部分代码:
   
 *Action.java
 
    /**
     * 转义数据库中存放的用户个人使用的编程语言
     * @return
     */
    public Converter getLanguageItemConverter(){
        return new Converter() {
            public Object convert(String value) throws Exception {
                String result = "";
                switch (Integer.parseInt(value)) {
                    case 1:
                        result = "Java";
                        break;
                    case 2:
                        result = "C";
                        break;
                    case 3:
                        result = "PHP";
                        break;
                }
                return result;
            }
        };
    }

 
通过以上代码,页面上最终将显示的结果是:
Java、C

6.<s:merge>标签

和<s:append>标签有点类型,不过叠加的形式不一样。

<s:append>是几个集合顺序叠加,而<s:merge>是将每个几个的第一项顺序叠加,第二项顺序叠加... 

叠加方式: 3 lists being merged, each list have 3 entries, the following willbe the logic.

  1. Display first element of the first list
  2. Display first element of the second list
  3. Display first element of the third 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

Name
Required
Default
Evaluated
Type
Description
idfalse falseStringDeprecated. Use 'var' instead
varfalse 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}"> <!--#myMergedIterator1是获取当前值栈上该引用指向的对象 -->
     <s:property />
</s:iterator>



7. <s:sort>标签

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 bepushed into the stack and poped at the end of this tag.

Parameters

Name
Required
Default
Evaluated
Type
Description
comparatortrue falsejava.util.ComparatorThe comparator to use
idfalse falseStringDeprecated. Use 'var' instead
sourcefalse falseStringThe iterable source to sort
varfalse falseStringThe name to store the resultant iterator into page context, if such name is supplied

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
   }
%>

sort标签的具体使用举例

1. Person object

Create a Person object with “firstName”, “lastName” and “age” properties.

Person.java

package com.mkyong.common;
 
public class Person{
 
	private String firstName;
	private String lastName;
	private int age;
 
	public Person(String firstName, String lastName, int age) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
 
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}


2. Comparator

Create 2 Comparator classes, to sort the Person’s “firstName” and “age” property.

FirstNameComparator.java

package com.mkyong.common;
 
import java.util.Comparator;
import com.mkyong.common.Person;
 
public class FirstNameComparator implements Comparator<Person> {
 
	public int compare(Person p1, Person p2) {
 
		String firstName1 = p1.getFirstName().toUpperCase();
		String firstName2 = p2.getFirstName().toUpperCase();
 
		return firstName1.compareTo(firstName2);
	}
}


AgeComparator.java

package com.mkyong.common;
 
import java.util.Comparator;
import com.mkyong.common.Person;
 
public class AgeComparator implements Comparator<Person> {
 
	public int compare(Person p1, Person p2) {
 
		return p1.getAge() - p2.getAge();
 
	}	
}

3. Action

Action class, initialize 6 Person objects, and add it into an ArrayList.

package com.mkyong.common.action;
 
import java.util.ArrayList;
import java.util.List;
 
import com.mkyong.common.Person;
import com.opensymphony.xwork2.ActionSupport;
 
public class SortTagAction extends ActionSupport{
 
	private List<Person> persons = new ArrayList<Person>();
 
	public String execute() {
 
		Person p1 = new Person("C-First", "C-Last", 40);
		Person p2 = new Person("A-First", "A-Last", 20);
		Person p3 = new Person("B-First", "B-Last", 10);
		Person p4 = new Person("F-First", "F-Last", 33);
		Person p5 = new Person("E-First", "E-Last", 22);
		Person p6 = new Person("D-First", "D-Last", 11);
 
		persons.add(p1);
		persons.add(p2);
		persons.add(p3);
		persons.add(p4);
		persons.add(p5);
		persons.add(p6);
 
		return SUCCESS;
	}
 
	public List<Person> getPersons() {
		return persons;
	}
	public void setPersons(List<Person> persons) {
		this.persons = persons;
	}
}


4. Sort tag example

A JSP page to show the use of sort tag to sort the List with “FirstNameComparator” and “AgeComparator“.

sort.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
 <html>
<head>
</head>
 
<body>
<h1>Struts 2 Sort tag example</h1>
 
<s:bean name="com.mkyong.common.FirstNameComparator" var="firstNameComparator" />
<s:bean name="com.mkyong.common.AgeComparator" var="ageComparator" />
 
<table>
<tr>
<td>
1. Display all persons (unsort).
<ol>
<s:iterator value="persons">
     <li><s:property value="firstName" />, 
         <s:property value="lastName" />, 
         <s:property value="age" />
     </li>
</s:iterator>
</ol>
</td>
 
<td>
2. Display all persons (sort with firstName).
<s:sort comparator="#firstNameComparator" source="persons">
<ol>
<s:iterator>
     <li><s:property value="firstName" />, 
         <s:property value="lastName" />, 
         <s:property value="age" />
     </li>
</s:iterator>
</ol>
</s:sort>
</td>
</tr>
 
<tr>
<td colspan="2">
3. Display all persons (sort with age).
<s:sort comparator="#ageComparator" source="persons">
<ol>
<s:iterator>
     <li><s:property value="firstName" />, 
         <s:property value="lastName" />, 
         <s:property value="age" />
     </li>
</s:iterator>
</ol>
</s:sort>
</td>
</tr>
</table>
 
</body>
</html>


5. struts.xml

Link it ~

<?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="sortTagAction" 
			class="com.mkyong.common.action.SortTagAction" >
			<result name="success">pages/sort.jsp</result>
		</action>
	</package>
</struts>



6.output
Struts 2 Sort tag example



8. <s:subset>标签

NOTE: JSP-TAG

A tag that takes an iterator and outputs a subset of it.(迭代并输出source集合的子集)

It delegates toorg.apache.struts2.util.SubsetIteratorFilter internally toperform the subset functionality.

Parameters

Name
Required
Default
Evaluated
Type
Description
countfalse falseIntegerIndicate 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 iterator
idfalse falseStringDeprecated. Use 'var' instead
sourcefalse falseStringIndicate the source of which the resulting subset iterator is to be derived base on
startfalse 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>




数据型Tag(Data Tag)



一、<s:set>标签

作用:将一个值赋给 特定范围内的变量。
            主要用于当一个复杂的表达式在该页面要被重复读取时,这时每次读取都比较耗时,所以设置一个变量,将其放在值栈。

特定范围包括:
                            
    application - the value will be set in application scope according to servlet spec. using the name as its key
    session - the value will be set in session scope according to servlet spec. using the name as key
    request - the value will be set in request scope according to servlet spec. using the name as key
    page - the value will be set in page scope according to servlet sepc. using the name as key
    action - the value will be set in the request scope and Struts' action context using the name as key
  

注意:

如果没指定scope范围,那默认的范围是action范围。

例子:

<s:bean name="xxx.person"id="person">
<s:param name="name"value="zhangsan"/>
<s:param name="age"value="29"/>
</s:bean>
<s:set name="personName" value="person.name"/>
Hello, <s:property value="#personName"/>. How are you?
用set标签的应用场景一般是value属性都是赋值表达式,如上。

但是,如果value中要赋的是常量或者字符串,如果直接

<s:set name="page2" value="hello"  scope="page"></s:set>    //Wrong way!!

这样在页面中是访问不到这个字符串,怎么样才能赋这个字符串常量值呢?加个单引号就搞定,这个也是我研究了半天才研究出来,如下:

<s:set name="page2"value=" 'hello ' " scope="page"></s:set>


二、s:action(不建议用)

作用:直接向某namespace下的action发送请求,整个页面的跳转。在ajax的大背景下,一般都通过js来发起异步请求,所以用的不多。

1.This tag enables developers to call actions directly from a JSP page by specifying the action name and an optionalnamespace.

2.The body content of the tag is used to render the results from the Action.

3.Any result processor definedfor this action in struts.xml will be ignored,unless the executeResult parameter is specified.(executeResult为true时,struts.xml配置有效,页面会跳转)

Parameters can be passed to the action using nested param tags.

<param name="color">blue</param> <-- (A) -->
<param name="color" value="blue"/> <-- (B) -->
In the first situation (A) the value would be evaluated to the stack as a java.lang.String object.And in situation (B) the value would be evaluated to the stack as ajava.lang.Object object.

参数:

Name
Required
Default
Evaluated
Type
Description
executeResultfalsefalsefalseBooleanWhether the result of this action (probably a view) should be executed/rendered
flushfalsetruefalseBooleanWhether the writer should be flush upon end of action component tag, default to true
idfalse falseStringDeprecated. Use 'var' instead
ignoreContextParamsfalsefalsefalseBooleanWhether the request parameters are to be included when the action is invoked
nametrue falseStringName of the action to be executed (without the extension suffix eg. .action)
namespacefalsenamespace from where tag is usedfalseStringNamespace for action to call
varfalse falseStringName used to reference the value pushed into the Value Stack

例子:

public class ActionTagAction extends ActionSupport {

 public String execute() throws Exception {
     return "done";
 }

 public String doDefault() throws Exception {
     ServletActionContext.getRequest().setAttribute("stringByAction", "This is a String put in by the action's doDefault()");
     return "done";
 }
}

<xwork> 这段可以被struts.xml中配置的action以及result代替
   ....
  <action name="actionTagAction1" class="tmjee.testing.ActionTagAction">
      <result name="done">success.jsp</result>
  </action>
   <action name="actionTagAction2" class="tmjee.testing.ActionTagAction" method="default">
      <result name="done">success.jsp</result>
  </action>
   ....
</xwork>

<div>The following action tag will execute result and include it in this page</div>
<br />
<s:action name="actionTagAction" executeResult="true" />
<br />
<div>The following action tag will do the same as above, but invokes method specialMethod in action</div>
<br />
<s:action name="actionTagAction!specialMethod" executeResult="true" />
<br />
<div>The following action tag will not execute result, but put a String in request scope
     under an id "stringByAction" which will be retrieved using property tag</div>
<s:action name="actionTagAction!default" executeResult="false" />
<s:property value="#attr.stringByAction" />



三、bean标签
例子:
<-- in jsp form -->
<s:bean name="org.apache.struts2.example.counter.SimpleCounter" var="counter">
  <s:param name="foo" value="BAR" />
  The value of foot is : <s:property value="foo"/>, when inside the bean tag <br />
</s:bean>
解释:
          1.实例化一个bean,该bean类名为SimpleCounter。
          2.针对这个实例,set foo字段 (setFoo('BAR')) 。(param做的功)
          3.将该对象 push到 Valuestack。

注:若使用 var attribute, bean将实例化到stack's Context(建议这么做).


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值