Struts2标签介绍

在介绍常用标志前,我想先从总体上,对Struts 1.xStruts 2.0的标志库(Tag Library)作比较。

Struts 1.x

Struts 2.0

分类

将标志库按功能分成HTMLTilesLogicBean等几部分

严格上来说,没有分类,所有标志都在URI“/struts-tags”命名空间下,不过,我们可以从功能上将其分为两大类:非UI标志和UI标志

表达式语言(expression languages

不支持嵌入语言(EL

OGNLJSTLGroovyVelcity

以上表格,纯属个人总结,如有所不足或错误,请不吝指正

好了,我要开始介绍常用(这里所谓的常用,是指在已往工作中使用Struts里经常用到的)的标志了。

要在JSP中使用Struts 2.0标志,先要指明标志的引入。通过在JSP的代码的顶部加入以下代码可以做到这点。
<%@taglib prefix="s" uri="/struts-tags" %>

  1. UI标志
    • ifelseifelse

描述:
执行基本的条件流转。

参数:

名称

必需

默认

类型

描述

备注

test

Boolean

决定标志里内容是否显示的表达式

else标志没有这个参数

id

Object/String

用来标识元素的id。在UI和表单中为HTMLid属性

例子:

<%@pagecontentType="text/html;charset=UTF-8"%>
<%@taglibprefix="s"uri="/struts-tags"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>ConditionFlow</title>
</head>
<body>
<h3>ConditionFlow</h3>
<!--
这里有点小技巧:
本来可以用#parameters.name[0]来获得,请求中name的值。但是,在我实现include例子时,
无论我用param标志给name赋任何值,#parameters里面不会含有任何值,所以#parameters.name也为空值。

其原因为:
当使用include标志时,被包含的页面(included)里#parameters拿到的是包含页面里的请求参数。

因此,这里必须手工调用request.getParameter("name")
-->

<s:setname="name"value="<%="'"+request.getParameter("name")+"'"%>"/>
<s:iftest="#name=='Max'">
Max'sfilehere
</s:if>
<s:elseiftest="#name=='Scott'">
Scott'sfilehere
</s:elseif>
<s:else>
Other'sfilehere
</s:else>
</body>
</html>

1 condition.jsp

  • iterator

描述:
用于遍历集合(java.util.Collection)或枚举值(java.util.Iterator)。

参数:

名称

必需

默认

类型

描述

status

String

如果设置此参数,一个IteratorStatus的实例将会压入每个遍历的堆栈

value

Object/String

要遍历的可枚举的(iteratable)数据源,或者将放入新列表(List)的对象

id

Object/String

用来标识元素的id。在UI和表单中为HTMLid属性

例子:

<%@pagecontentType="text/html;charset=UTF-8"%>
<%@pageimport="java.util.List"%>
<%@pageimport="java.util.ArrayList"%>
<%@taglibprefix="s"uri="/struts-tags"%>

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<%
Listlist=
newArrayList();
list.add("Max");
list.add("Scott");
list.add("Jeffry");
list.add("Joe");
list.add("Kelvin");
request.setAttribute("names",list);
%>
<html>
<head>
<title>Iterator</title>
</head>
<body>
<h3>Names:</h3>
<!--
1
、此处的空property元素用于获得当前iterator的值
2
status被设成stuts,在iterator的里面就可以通过#stuts取得IteratorStatus的对象。IteratorStatus类包含当前序号信息,如是否第一个或最后一个,是否为奇数序号。这些信息在我们做格式化的时候,显得非常有用。
-->

<ol>
<s:iteratorvalue="#request.names"status="stuts">
<s:iftest="#stuts.odd==true">
<li>White<s:property/></li>
</s:if>
<s:else>
<listyle="background-color:gray"><s:property/></li>
</s:else>
</s:iterator>
</ol>
</body>
</html>

2 iterator.jsp

o i18n

描述:
加载资源包到值堆栈。它可以允许text标志访问任何资源包的信息,而不只当前action相关联的资源包。

参数:

名称

必需

默认

类型

描述

value

Object/String

资源包的类路径(如com.xxxx.resources.AppMsg

id

Object/String

用来标识元素的id。在UI和表单中为HTMLid属性

例子:

HelloWorld=HelloWrold!

3 classes/ ApplicationMessages.properties

<%@pagecontentType="text/html;charset=UTF-8"%>
<%@taglibprefix="s"uri="/struts-tags"%>

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>Internationization</title>
</head>
<body>
<h3>
<s:i18nname="ApplicationMessages">
<s:textname="HelloWorld"/>
</s:i18n>
</h3>
</body>
</html>

3 i18n.jsp

o include

描述:
包含一个servlet的输出(servletjsp的页面)。

参数:

名称

必需

默认

类型

描述

value

String

要包含的jspservlet

id

Object/String

用来标识元素的id。在UI和表单中为HTMLid属性

例子:

<%@pagecontentType="text/html;charset=UTF-8"%>
<%@taglibprefix="s"uri="/struts-tags"%>

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>Iterator</title>
</head>
<body>
<h3>InteratorPage</h3>
<s:includevalue="/condition.jsp">
<s:paramname="name">Max</s:param>
</s:include>
<h3>i18n</h3>
<s:includevalue="/i18n.jsp"/>
</body>
</html>

4 include.jsp

o param

描述:
为其他标签提供参数,比如include标签和bean标签. 参数的name属性是可选的,如果提供,会调用Component的方法addParameter(String, Object), 如果不提供,则外层嵌套标签必须实现UnnamedParametric接口(TextTag)

value的提供有两种方式,通过value属性或者标签中间的text,不同之处我们看一下例子:

<param name="color">blue</param><!-- (A) -->

<param name="color" value="blue"/><!-- (B) -->
(A)
参数值会以String的格式放入statck.
(B)
该值会以java.lang.Object的格式放入statck.

参数:

名称

必需

默认

类型

描述

name

String

参数名

value

String

value表达式

id

Object/String

用来标识元素的id。在UI和表单中为HTMLid属性

例子:
请参考例4

o set

描述:
set
标签赋予变量一个特定范围内的值。当希望给一个变量赋一个复杂的表达式,每次访问该变量而不是复杂的表达式时用到。其在两种情况下非常有用: 复杂的表达式很耗时 (性能提升) 或者很难理解 (代码可读性提高)

参数:

名称

必需

默认

类型

描述

name

String

变量名字

scope

String

变量作用域,可以为application, session, request, page, action.

value

Object/String

将会赋给变量的值

id

Object/String

用来标识元素的id。在UI和表单中为HTMLid属性

例子:
请参考例1

o text

描述:
支持国际化信息的标签。国际化信息必须放在一个和当前action同名的resource bundle,如果没有找到相应message,tag body将被当作默认message,如果没有tag body,messagename会被作为默认message

参数:

名称

必需

默认

类型

描述

name

String

资源属性的名字

id

Object/String

用来标识元素的id。在UI和表单中为HTMLid属性

例子:
请参考例3

o url

描述:
该标签用于创建url,可以通过"param"标签提供request参数。

includeParams的值时'all'或者'get', param标签中定义的参数将有优先权,也就是说其会覆盖其他同名参数的值。

参数: 略

例子:

<%@pagecontentType="text/html;charset=UTF-8"%>
<%@taglibprefix="s"uri="/struts-tags"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>URL</title>
</head>
<body>
<h3>URL</h3>
<ahref='<s:urlvalue="/i18n.jsp"/>'>i18n</a><br/>
<s:urlid="url"value="/condition.jsp">
<s:paramname="name">Max</s:param>
</s:url>
<s:ahref="%{url}">if/elseif/else</s:a>
</body>
</html>

5 url.jsp

o property

描述:
得到'value'的属性,如果value没提供,默认为堆栈顶端的元素。

参数:

名称

必需

默认

类型

描述

default

String

如果属性是null则显示的default

escape

true

Booelean

是否escape HTML

value

栈顶

Object

要显示的值

id

Object/String

用来标识元素的id。在UI和表单中为HTMLid属性

例子:
请参考例2

  1. UI标志

UI标志又可以分为表单UI和非表单UI两部分。表单UI部分基本与Struts 1.x相同,都是对HTML表单元素的包装。不过,Struts 2.0加了几个我们经常在项目中用到的控件如:datepickerdoubleselecttimepickeroptiontransferselect等。因为这些标志很多都经常用到,而且参数也很多,要在一篇文章详细说明并非易事。

需要深入了解这些标志的朋友,可以到以下查看以下网址:
http://wiki.javascud.org/display/ww2cndoc/Tags WebWork2
文档中文化计划(中文)
http://cwiki.apache.org/WW/tag-reference.html Tag Developers Guide
(英文)
本文有相当的内容也来自这两处。

在此,我虽然不能够详细讲述这些标志,但是可以与大家分享一个来Struts 2.0 Show Case一个例子。

/**//*
*$Id:UITagExample.java4203852006-07-1000:57:05Zmrdon$
*
*Copyright2006TheApacheSoftwareFoundation.
*
*LicensedundertheApacheLicense,Version2.0(the"License");
*youmaynotusethisfileexceptincompliancewiththeLicense.
*YoumayobtainacopyoftheLicenseat
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
*distributedundertheLicenseisdistributedonan"ASIS"BASIS,
*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
*SeetheLicenseforthespecificlanguagegoverningpermissionsand
*limitationsundertheLicense.
*/

packageorg.apache.struts2.showcase;

importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionSupport;
importcom.opensymphony.xwork2.Validateable;
importcom.opensymphony.xwork2.util.OgnlValueStack;

importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importjava.io.File;

/***//**
*/

publicclassUITagExampleextendsActionSupportimplementsValidateable{

privatestaticfinallongserialVersionUID=-94044809860988047L;
Stringname;
Datebirthday;
Stringbio;
StringfavoriteColor;
Listfriends;
booleanlegalAge;
Stringstate;
Stringregion;
Filepicture;
StringpictureContentType;
StringpictureFileName;
StringfavouriteLanguage;
StringfavouriteVehicalType="MotorcycleKey";
StringfavouriteVehicalSpecific="YamahaKey";

ListleftSideCartoonCharacters;
ListrightSideCartoonCharacters;

ListfavouriteLanguages=
newArrayList();
ListvehicalTypeList=
newArrayList();
MapvehicalSpecificMap=
newHashMap();

Stringthoughts;

publicUITagExample(){
favouriteLanguages.add(
newLanguage("EnglishKey","EnglishLanguage"));
favouriteLanguages.add(
newLanguage("FrenchKey","FrenchLanguage"));
favouriteLanguages.add(
newLanguage("SpanishKey","SpanishLanguage"));

VehicalTypecar=
newVehicalType("CarKey","Car");
VehicalTypemotorcycle=
newVehicalType("MotorcycleKey","Motorcycle");
vehicalTypeList.add(car);
vehicalTypeList.add(motorcycle);

Listcars=
newArrayList();
cars.add(
newVehicalSpecific("MercedesKey","Mercedes"));
cars.add(
newVehicalSpecific("HondaKey","Honda"));
cars.add(
newVehicalSpecific("FordKey","Ford"));

Listmotorcycles=
newArrayList();
motorcycles.add(
newVehicalSpecific("SuzukiKey","Suzuki"));
motorcycles.add(
newVehicalSpecific("YamahaKey","Yamaha"));

vehicalSpecificMap.put(car,cars);
vehicalSpecificMap.put(motorcycle,motorcycles);
}

publicListgetLeftSideCartoonCharacters(){
returnleftSideCartoonCharacters;
}
publicvoidsetLeftSideCartoonCharacters(ListleftSideCartoonCharacters){
this.leftSideCartoonCharacters=leftSideCartoonCharacters;
}

publicListgetRightSideCartoonCharacters(){
returnrightSideCartoonCharacters;
}
publicvoidsetRightSideCartoonCharacters(ListrightSideCartoonCharacters){
this.rightSideCartoonCharacters=rightSideCartoonCharacters;
}

publicStringgetFavouriteVehicalType(){
returnfavouriteVehicalType;
}

publicvoidsetFavouriteVehicalType(StringfavouriteVehicalType){
this.favouriteVehicalType=favouriteVehicalType;
}

publicStringgetFavouriteVehicalSpecific(){
returnfavouriteVehicalSpecific;
}

publicvoidsetFavouriteVehicalSpecific(StringfavouriteVehicalSpecific){
this.favouriteVehicalSpecific=favouriteVehicalSpecific;
}

publicListgetVehicalTypeList(){
returnvehicalTypeList;
}

publicListgetVehicalSpecificList(){
OgnlValueStackstack=ServletActionContext.getValueStack(ServletActionContext.getRequest());
ObjectvehicalType=stack.findValue("top");
if(vehicalType!=null&&vehicalTypeinstanceofVehicalType){
Listl=(List)vehicalSpecificMap.get(vehicalType);
returnl;
}
returnCollections.EMPTY_LIST;
}

publicListgetFavouriteLanguages(){
returnfavouriteLanguages;
}

publicStringexecute()throwsException{
returnSUCCESS;
}

/**//*GettersandSetters*/

publicStringdoSubmit(){
returnSUCCESS;
}

//===innerclass
publicstaticclassLanguage{
Stringdescription;
Stringkey;

publicLanguage(Stringkey,Stringdescription){
this.key=key;
this.description=description;
}

publicStringgetKey(){
returnkey;
}
publicStringgetDescription(){
returndescription;
}

}

publicstaticclassVehicalType{
Stringkey;
Stringdescription;
publicVehicalType(Stringkey,Stringdescription){
this.key=key;
this.description=description;
}

publicStringgetKey(){returnthis.key;}
publicStringgetDescription(){returnthis.description;}

publicbooleanequals(Objectobj){
if(!(objinstanceofVehicalType)){
returnfalse;
}
else{
returnkey.equals(((VehicalType)obj).getKey());
}
}

publicinthashCode(){
returnkey.hashCode();
}
}

publicstaticclassVehicalSpecific{
Stringkey;
Stringdescription;
publicVehicalSpecific(Stringkey,Stringdescription){
this.key=key;
this.description=description;
}

publicStringgetKey(){returnthis.key;}
publicStringgetDescription(){returnthis.description;}

publicbooleanequals(Objectobj){
if(!(objinstanceofVehicalSpecific)){
returnfalse;
}
else{
returnkey.equals(((VehicalSpecific)obj).getKey());
}
}

publicinthashCode(){
returnkey.hashCode();
}
}
}

6 org.apache.struts2.showcase.UITagExample.java

<%@pagecontentType="text/html;charset=UTF-8"pageEncoding="UTF-8"%>
<%@taglibprefix="s"uri="/struts-tags"%>
<html>
<head>
<title>UITagsExample</title>
<s:head/>
</head>
<body>

<s:actionerror/>
<s:actionmessage/>
<s:fielderror/>

<s:formaction="exampleSubmit"method="post"enctype="multipart/form-data"tooltipConfig="#{'jsTooltipEnabled':'true'}">
<s:textfield
label="Name"
name
="name"
tooltip
="EnteryourNamehere"/>

<s:datepicker
tooltip="SelectYourBirthday"
label
="Birthday"
name
="birthday"/>

<s:textarea
tooltip="EnteryourBiography"
label
="Biograph"
name
="bio"
cols
="20"
rows
="3"/>

<s:select
tooltip="ChooseYourFavouriteColor"
label
="FavoriteColor"
list
="{'Red','Blue','Green'}"
name
="favoriteColor"
emptyOption
="true"
headerKey
="None"
headerValue
="None"/>

<s:select
tooltip="ChooseYourFavouriteLanguage"
label
="FavouriteLanguage"
list
="favouriteLanguages"
name
="favouriteLanguage"
listKey
="key"
listValue
="description"
emptyOption
="true"
headerKey
="None"
headerValue
="None"/>

<s:checkboxlist
tooltip="ChooseyourFriends"
label
="Friends"
list
="{'Patrick','Jason','Jay','Toby','Rene'}"
name
="friends"/>

<s:checkbox
tooltip="ConfirmedthatyourareOver18"
label
="Age18+"
name
="legalAge"/>

<s:doubleselect
tooltip="ChooseYourState"
label
="State"
name
="region"list="{'North','South'}"
value
="'South'"
doubleValue
="'Florida'"
doubleList
="top=='North'?{'Oregon','Washington'}:{'Texas','Florida'}"
doubleName
="state"
headerKey
="-1"
headerValue
="----------PleaseSelect----------"
emptyOption
="true"/>

<s:doubleselect
tooltip="ChooseyourVehical"
label
="FavouriteVehical"
name
="favouriteVehicalType"
list
="vehicalTypeList"
listKey
="key"
listValue
="description"
value
="'MotorcycleKey'"
doubleValue
="'YamahaKey'"
doubleList
="vehicalSpecificList"
doubleListKey
="key"
doubleListValue
="description"
doubleName
="favouriteVehicalSpecific"headerKey="-1"
headerValue
="----------PleaseSelect----------"
emptyOption
="true"/>

<s:file
tooltip="UploadYourPicture"
label
="Picture"
name
="picture"/>

<s:optiontransferselect
tooltip="SelectYourFavouriteCartoonCharacters"
label
="FavouriteCartoonsCharacters"
name
="leftSideCartoonCharacters"
leftTitle
="LeftTitle"
rightTitle
="RightTitle"
list
="{'Popeye','He-Man','Spiderman'}"
multiple
="true"
headerKey
="headerKey"
headerValue
="---PleaseSelect---"
emptyOption
="true"
doubleList
="{'Superman','MickeyMouse','DonaldDuck'}"
doubleName
="rightSideCartoonCharacters"
doubleHeaderKey
="doubleHeaderKey"
doubleHeaderValue
="---PleaseSelect---"
doubleEmptyOption
="true"
doubleMultiple
="true"/>

<s:textarea
label="YourThougths"
name
="thoughts"
tooltip
="Enteryourthoughtshere"/>

<s:submitonclick="alert('aaaa');"/>
<s:resetonclick="alert('bbbb');"/>
</s:form>

</body>
</html>

6 example.jsp

<actionname="example"class="org.apache.struts2.showcase.UITagExample">
<result>example.jsp</result>
<resultname="input">example.jsp</result>
</action>

6 struts.xml代码片段

你可能感兴趣的:(struts2标签)