在上一篇文章《為Struts 2.0做好準(zhǔn)備》中,我過(guò)于詳細(xì)地介紹了Struts 2.0開發(fā)環(huán)境和運(yùn)行環(huán)境的配置,所以,本文很少涉及的以上兩方面的細(xì)節(jié)。如果,您看完《為Struts 2.0做好準(zhǔn)備》后,還有什么不明白,或者沒法運(yùn)行文中例子,請(qǐng)聯(lián)系我。我的E-MAIL:Max.M.Yuan@gmail.com。
在介紹常用標(biāo)志前,我想先從總體上,對(duì)Struts 1.x與Struts 2.0的標(biāo)志庫(kù)(Tag Library)作比較。
|
Struts 1.x |
Struts 2.0 |
分類 |
將標(biāo)志庫(kù)按功能分成HTML、Tiles、Logic和Bean等幾部分 |
嚴(yán)格上來(lái)說(shuō),沒有分類,所有標(biāo)志都在URI為“/struts-tags”命名空間下,不過(guò),我們可以從功能上將其分為兩大類:非UI標(biāo)志和UI標(biāo)志 |
表達(dá)式語(yǔ)言(expression languages) |
不支持嵌入語(yǔ)言(EL) |
OGNL、JSTL、Groovy和Velcity |
以上表格,純屬個(gè)人總結(jié),如有所不足或錯(cuò)誤,請(qǐng)不吝指正
好了,我要開始介紹“常用”(這里所謂的“常用”,是指在已往工作中使用Struts里經(jīng)常用到的)的標(biāo)志了。
|
要在JSP中使用Struts 2.0標(biāo)志,先要指明標(biāo)志的引入。通過(guò)在JSP的代碼的頂部加入以下代碼可以做到這點(diǎn)。 <%@taglib prefix="s" uri="/struts-tags" %> |
- 非UI標(biāo)志
- if、elseif和else
描述: 執(zhí)行基本的條件流轉(zhuǎn)。
參數(shù):
名稱 |
必需 |
默認(rèn) |
類型 |
描述 |
備注 |
test |
是 |
|
Boolean |
決定標(biāo)志里內(nèi)容是否顯示的表達(dá)式 |
else標(biāo)志沒有這個(gè)參數(shù) |
id |
否 |
|
Object/String |
用來(lái)標(biāo)識(shí)元素的id。在UI和表單中為HTML的id屬性 |
|
例子:
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Condition Flow</title> </head> <body> <h3>Condition Flow</h3> <!-- 這里有點(diǎn)小技巧: 本來(lái)可以用#parameters.name[0]來(lái)獲得,請(qǐng)求中name的值。但是,在我實(shí)現(xiàn)include例子時(shí), 無(wú)論我用param標(biāo)志給name賦任何值,#parameters里面不會(huì)含有任何值,所以#parameters.name也為空值。 其原因?yàn)椋?br> 當(dāng)使用include標(biāo)志時(shí),被包含的頁(yè)面(included)里#parameters拿到的是包含頁(yè)面里的請(qǐng)求參數(shù)。 因此,這里必須手工調(diào)用request.getParameter("name")。 --> <s:set name="name" value="<%= "'" + request.getParameter("name") + "'" %>" /> <s:if test="#name == 'Max'"> Max's file here </s:if> <s:elseif test="#name == 'Scott'"> Scott's file here </s:elseif> <s:else> Other's file here </s:else> </body> </html>
例1 condition.jsp
- iterator
描述: 用于遍歷集合(java.util.Collection)或枚舉值(java.util.Iterator)。
參數(shù):
名稱 |
必需 |
默認(rèn) |
類型 |
描述 |
status |
否 |
|
String |
如果設(shè)置此參數(shù),一個(gè)IteratorStatus的實(shí)例將會(huì)壓入每個(gè)遍歷的堆棧 |
value |
否 |
|
Object/String |
要遍歷的可枚舉的(iteratable)數(shù)據(jù)源,或者將放入新列表(List)的對(duì)象 |
id |
否 |
|
Object/String |
用來(lái)標(biāo)識(shí)元素的id。在UI和表單中為HTML的id屬性 |
例子:
<%@ page contentType="text/html; charset=UTF-8" %> <%@ page import="java.util.List" %> <%@ page import="java.util.ArrayList" %> <%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <% List list = new ArrayList(); 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元素用于獲得當(dāng)前iterator的值 2、status被設(shè)成stuts,在iterator的里面就可以通過(guò)#stuts取得IteratorStatus的對(duì)象。IteratorStatus類包含當(dāng)前序號(hào)信息,如是否第一個(gè)或最后一個(gè),是否為奇數(shù)序號(hào)。這些信息在我們做格式化的時(shí)候,顯得非常有用。 --> <ol> <s:iterator value="#request.names" status="stuts"> <s:if test="#stuts.odd == true"> <li>White <s:property /></li> </s:if> <s:else> <li style="background-color:gray"><s:property /></li> </s:else> </s:iterator> </ol> </body> </html>
例2 iterator.jsp
- i18n
描述: 加載資源包到值堆棧。它可以允許text標(biāo)志訪問(wèn)任何資源包的信息,而不只當(dāng)前action相關(guān)聯(lián)的資源包。
參數(shù):
名稱 |
必需 |
默認(rèn) |
類型 |
描述 |
value |
是 |
|
Object/String |
資源包的類路徑(如com.xxxx.resources.AppMsg) |
id |
否 |
|
Object/String |
用來(lái)標(biāo)識(shí)元素的id。在UI和表單中為HTML的id屬性 |
例子:
HelloWorld=Hello Wrold!
例3 classes\ ApplicationMessages.properties
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Internationization</title> </head> <body> <h3> <s:i18n name="ApplicationMessages"> <s:text name="HelloWorld" /> </s:i18n> </h3> </body> </html>
例3 i18n.jsp
- include
描述: 包含一個(gè)servlet的輸出(servlet或jsp的頁(yè)面)。
參數(shù):
名稱 |
必需 |
默認(rèn) |
類型 |
描述 |
value |
是 |
|
String |
要包含的jsp或servlet |
id |
否 |
|
Object/String |
用來(lái)標(biāo)識(shí)元素的id。在UI和表單中為HTML的id屬性 |
例子:
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Iterator</title> </head> <body> <h3>Interator Page</h3> <s:include value="/condition.jsp"> <s:param name="name">Max</s:param> </s:include> <h3>i18n</h3> <s:include value="/i18n.jsp" /> </body> </html>
例4 include.jsp
- param
描述: 為其他標(biāo)簽提供參數(shù),比如include標(biāo)簽和bean標(biāo)簽. 參數(shù)的name屬性是可選的,如果提供,會(huì)調(diào)用Component的方法addParameter(String, Object), 如果不提供,則外層嵌套標(biāo)簽必須實(shí)現(xiàn)UnnamedParametric接口(如TextTag)。
 |
value的提供有兩種方式,通過(guò)value屬性或者標(biāo)簽中間的text,不同之處我們看一下例子:
<param name="color">blue</param><!-- (A) -->
<param name="color" value="blue"/><!-- (B) --> (A)參數(shù)值會(huì)以String的格式放入statck. (B)該值會(huì)以java.lang.Object的格式放入statck.
|
參數(shù):
名稱 |
必需 |
默認(rèn) |
類型 |
描述 |
name |
否 |
|
String |
參數(shù)名 |
value |
否 |
|
String |
value表達(dá)式 |
id |
否 |
|
Object/String |
用來(lái)標(biāo)識(shí)元素的id。在UI和表單中為HTML的id屬性 |
例子: 請(qǐng)參考例4。
- set
描述: set標(biāo)簽賦予變量一個(gè)特定范圍內(nèi)的值。當(dāng)希望給一個(gè)變量賦一個(gè)復(fù)雜的表達(dá)式,每次訪問(wèn)該變量而不是復(fù)雜的表達(dá)式時(shí)用到。其在兩種情況下非常有用: 復(fù)雜的表達(dá)式很耗時(shí) (性能提升) 或者很難理解 (代碼可讀性提高)。
參數(shù):
名稱 |
必需 |
默認(rèn) |
類型 |
描述 |
name |
是 |
|
String |
變量名字 |
scope |
否 |
|
String |
變量作用域,可以為application, session, request, page, 或action. |
value |
否 |
|
Object/String |
將會(huì)賦給變量的值 |
id |
否 |
|
Object/String |
用來(lái)標(biāo)識(shí)元素的id。在UI和表單中為HTML的id屬性 |
例子: 請(qǐng)參考例1。
- text
描述: 支持國(guó)際化信息的標(biāo)簽。國(guó)際化信息必須放在一個(gè)和當(dāng)前action同名的resource bundle中,如果沒有找到相應(yīng)message,tag body將被當(dāng)作默認(rèn)message,如果沒有tag body,message的name會(huì)被作為默認(rèn)message。
參數(shù):
名稱 |
必需 |
默認(rèn) |
類型 |
描述 |
name |
是 |
|
String |
資源屬性的名字 |
id |
否 |
|
Object/String |
用來(lái)標(biāo)識(shí)元素的id。在UI和表單中為HTML的id屬性 |
例子: 請(qǐng)參考例3。
- url
描述: 該標(biāo)簽用于創(chuàng)建url,可以通過(guò)"param"標(biāo)簽提供request參數(shù)。
 |
當(dāng)includeParams的值時(shí)'all'或者'get', param標(biāo)簽中定義的參數(shù)將有優(yōu)先權(quán),也就是說(shuō)其會(huì)覆蓋其他同名參數(shù)的值。 |
參數(shù): 略
例子:
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>URL</title> </head> <body> <h3>URL</h3> <a href='<s:url value="/i18n.jsp" />'>i18n</a><br /> <s:url id="url" value="/condition.jsp"> <s:param name="name">Max</s:param> </s:url> <s:a href="%{url}">if\elseif\else</s:a> </body> </html>
例5 url.jsp
- property
描述: 得到'value'的屬性,如果value沒提供,默認(rèn)為堆棧頂端的元素。
參數(shù):
名稱 |
必需 |
默認(rèn) |
類型 |
描述 |
default |
否 |
|
String |
如果屬性是null則顯示的default值 |
escape |
否 |
true |
Booelean |
是否escape HTML |
value |
否 |
棧頂 |
Object |
要顯示的值 |
id |
否 |
|
Object/String |
用來(lái)標(biāo)識(shí)元素的id。在UI和表單中為HTML的id屬性 |
例子: 請(qǐng)參考例2。
- UI標(biāo)志
UI標(biāo)志又可以分為表單UI和非表單UI兩部分。表單UI部分基本與Struts 1.x相同,都是對(duì)HTML表單元素的包裝。不過(guò),Struts 2.0加了幾個(gè)我們經(jīng)常在項(xiàng)目中用到的控件如:datepicker、doubleselect、timepicker、optiontransferselect等。因?yàn)檫@些標(biāo)志很多都經(jīng)常用到,而且參數(shù)也很多,要在一篇文章詳細(xì)說(shuō)明并非易事。
在此,我雖然不能夠詳細(xì)講述這些標(biāo)志,但是可以與大家分享一個(gè)來(lái)Struts 2.0 Show Case一個(gè)例子。
 /**//*
* $Id: UITagExample.java 420385 2006-07-10 00:57:05Z mrdon $
*
* Copyright 2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.struts2.showcase;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Validateable;
import com.opensymphony.xwork2.util.OgnlValueStack;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.File;

 /** *//**
*/
 public class UITagExample extends ActionSupport implements Validateable {
private static final long serialVersionUID = -94044809860988047L;
String name;
Date birthday;
String bio;
String favoriteColor;
List friends;
boolean legalAge;
String state;
String region;
File picture;
String pictureContentType;
String pictureFileName;
String favouriteLanguage;
String favouriteVehicalType = "MotorcycleKey";
String favouriteVehicalSpecific = "YamahaKey";
List leftSideCartoonCharacters;
List rightSideCartoonCharacters;
List favouriteLanguages = new ArrayList();
List vehicalTypeList = new ArrayList();
Map vehicalSpecificMap = new HashMap();
String thoughts;
 public UITagExample() {
favouriteLanguages.add(new Language("EnglishKey", "English Language"));
favouriteLanguages.add(new Language("FrenchKey", "French Language"));
favouriteLanguages.add(new Language("SpanishKey", "Spanish Language"));
VehicalType car = new VehicalType("CarKey", "Car");
VehicalType motorcycle = new VehicalType("MotorcycleKey", "Motorcycle");
vehicalTypeList.add(car);
vehicalTypeList.add(motorcycle);
List cars = new ArrayList();
cars.add(new VehicalSpecific("MercedesKey", "Mercedes"));
cars.add(new VehicalSpecific("HondaKey", "Honda"));
cars.add(new VehicalSpecific("FordKey", "Ford"));
List motorcycles = new ArrayList();
motorcycles.add(new VehicalSpecific("SuzukiKey", "Suzuki"));
motorcycles.add(new VehicalSpecific("YamahaKey", "Yamaha"));
vehicalSpecificMap.put(car, cars);
vehicalSpecificMap.put(motorcycle, motorcycles);
}
 public List getLeftSideCartoonCharacters() {
return leftSideCartoonCharacters;
}
 public void setLeftSideCartoonCharacters(List leftSideCartoonCharacters) {
this.leftSideCartoonCharacters = leftSideCartoonCharacters;
}
 public List getRightSideCartoonCharacters() {
return rightSideCartoonCharacters;
}
 public void setRightSideCartoonCharacters(List rightSideCartoonCharacters) {
this.rightSideCartoonCharacters = rightSideCartoonCharacters;
}
 public String getFavouriteVehicalType() {
return favouriteVehicalType;
}
 public void setFavouriteVehicalType(String favouriteVehicalType) {
this.favouriteVehicalType = favouriteVehicalType;
}
 public String getFavouriteVehicalSpecific() {
return favouriteVehicalSpecific;
}
 public void setFavouriteVehicalSpecific(String favouriteVehicalSpecific) {
this.favouriteVehicalSpecific = favouriteVehicalSpecific;
}
 public List getVehicalTypeList() {
return vehicalTypeList;
}
 public List getVehicalSpecificList() {
OgnlValueStack stack = ServletActionContext.getValueStack(ServletActionContext.getRequest());
Object vehicalType = stack.findValue("top");
 if (vehicalType != null && vehicalType instanceof VehicalType) {
List l = (List) vehicalSpecificMap.get(vehicalType);
return l;
}
return Collections.EMPTY_LIST;
}
 public List getFavouriteLanguages() {
return favouriteLanguages;
}

 public String execute() throws Exception {
return SUCCESS;
}

 /**//* Getters and Setters */
 public String doSubmit() {
return SUCCESS;
}
// === inner class
 public static class Language {
String description;
String key;
 public Language(String key, String description) {
this.key = key;
this.description = description;
}
 public String getKey() {
return key;
}
 public String getDescription() {
return description;
}
}
 public static class VehicalType {
String key;
String description;
 public VehicalType(String key, String description) {
this.key = key;
this.description = description;
}
 public String getKey() { return this.key; }
 public String getDescription() { return this.description; }
 public boolean equals(Object obj) {
 if (! (obj instanceof VehicalType)) {
return false;
}
 else {
return key.equals(((VehicalType)obj).getKey());
}
}
 public int hashCode() {
return key.hashCode();
}
}
 public static class VehicalSpecific {
String key;
String description;
 public VehicalSpecific(String key, String description) {
this.key = key;
this.description = description;
}
 public String getKey() { return this.key; }
 public String getDescription() { return this.description; }
 public boolean equals(Object obj) {
 if (! (obj instanceof VehicalSpecific)) {
return false;
}
 else {
return key.equals(((VehicalSpecific)obj).getKey());
}
}
 public int hashCode() {
return key.hashCode();
}
}
}
例6 org.apache.struts2.showcase.UITagExample.java
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>UI Tags Example</title> <s:head/> </head> <body>
<s:actionerror/> <s:actionmessage/> <s:fielderror />
<s:form action="exampleSubmit" method="post" enctype="multipart/form-data" tooltipConfig="#{'jsTooltipEnabled':'true'}"> <s:textfield label="Name" name="name" tooltip="Enter your Name here" />
<s:datepicker tooltip="Select Your Birthday" label="Birthday" name="birthday" />
<s:textarea tooltip="Enter your Biography" label="Biograph" name="bio" cols="20" rows="3"/>
<s:select tooltip="Choose Your Favourite Color" label="Favorite Color" list="{'Red', 'Blue', 'Green'}" name="favoriteColor" emptyOption="true" headerKey="None" headerValue="None"/>
<s:select tooltip="Choose Your Favourite Language" label="Favourite Language" list="favouriteLanguages" name="favouriteLanguage" listKey="key" listValue="description" emptyOption="true" headerKey="None" headerValue="None"/>
<s:checkboxlist tooltip="Choose your Friends" label="Friends" list="{'Patrick', 'Jason', 'Jay', 'Toby', 'Rene'}" name="friends"/>
<s:checkbox tooltip="Confirmed that your are Over 18" label="Age 18+" name="legalAge"/>
<s:doubleselect tooltip="Choose Your State" label="State" name="region" list="{'North', 'South'}" value="'South'" doubleValue="'Florida'" doubleList="top == 'North' ? {'Oregon', 'Washington'} : {'Texas', 'Florida'}" doubleName="state" headerKey="-1" headerValue="---------- Please Select ----------" emptyOption="true" />
<s:doubleselect tooltip="Choose your Vehical" label="Favourite Vehical" name="favouriteVehicalType" list="vehicalTypeList" listKey="key" listValue="description" value="'MotorcycleKey'" doubleValue="'YamahaKey'" doubleList="vehicalSpecificList" doubleListKey="key" doubleListValue="description" doubleName="favouriteVehicalSpecific" headerKey="-1" headerValue="---------- Please Select ----------" emptyOption="true" />
<s:file tooltip="Upload Your Picture" label="Picture" name="picture" /> <s:optiontransferselect tooltip="Select Your Favourite Cartoon Characters" label="Favourite Cartoons Characters" name="leftSideCartoonCharacters" leftTitle="Left Title" rightTitle="Right Title" list="{'Popeye', 'He-Man', 'Spiderman'}" multiple="true" headerKey="headerKey" headerValue="--- Please Select ---" emptyOption="true" doubleList="{'Superman', 'Mickey Mouse', 'Donald Duck'}" doubleName="rightSideCartoonCharacters" doubleHeaderKey="doubleHeaderKey" doubleHeaderValue="--- Please Select ---" doubleEmptyOption="true" doubleMultiple="true" /> <s:textarea label="Your Thougths" name="thoughts" tooltip="Enter your thoughts here" /> <s:submit onclick="alert('aaaa');" /> <s:reset onclick="alert('bbbb');" /> </s:form> </body> </html>
例6 example.jsp
<action name="example" class="org.apache.struts2.showcase.UITagExample"> <result>example.jsp</result> <result name="input">example.jsp</result> </action>
例6 struts.xml代碼片段
posted on 2006-10-18 12:02 Max 閱讀(4673) 評(píng)論(21) 編輯 收藏 引用 所屬分類: Struts 2.0系列
|