在上一篇文章《為Struts 2.0做好準備》中,我過于詳細地介紹了Struts 2.0開發環境和運行環境的配置,所以,本文很少涉及的以上兩方面的細節。如果,您看完《為Struts 2.0做好準備》后,還有什么不明白,或者沒法運行文中例子,請聯系我。我的E-MAIL:Max.M.Yuan@gmail.com。
在介紹常用標志前,我想先從總體上,對Struts 1.x與Struts 2.0的標志庫(Tag Library)作比較。
|
Struts 1.x |
Struts 2.0 |
分類 |
將標志庫按功能分成HTML、Tiles、Logic和Bean等幾部分 |
嚴格上來說,沒有分類,所有標志都在URI為“/struts-tags”命名空間下,不過,我們可以從功能上將其分為兩大類:非UI標志和UI標志 |
表達式語言(expression languages) |
不支持嵌入語言(EL) |
OGNL、JSTL、Groovy和Velcity |
以上表格,純屬個人總結,如有所不足或錯誤,請不吝指正
好了,我要開始介紹“常用”(這里所謂的“常用”,是指在已往工作中使用Struts里經常用到的)的標志了。
|
要在JSP中使用Struts 2.0標志,先要指明標志的引入。通過在JSP的代碼的頂部加入以下代碼可以做到這點。 <%@taglib prefix="s" uri="/struts-tags" %> |
- 非UI標志
- if、elseif和else
描述: 執行基本的條件流轉。
參數:
名稱 |
必需 |
默認 |
類型 |
描述 |
備注 |
test |
是 |
|
Boolean |
決定標志里內容是否顯示的表達式 |
else標志沒有這個參數 |
id |
否 |
|
Object/String |
用來標識元素的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> <!-- 這里有點小技巧: 本來可以用#parameters.name[0]來獲得,請求中name的值。但是,在我實現include例子時, 無論我用param標志給name賦任何值,#parameters里面不會含有任何值,所以#parameters.name也為空值。 其原因為: 當使用include標志時,被包含的頁面(included)里#parameters拿到的是包含頁面里的請求參數。 因此,這里必須手工調用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)。
參數:
名稱 |
必需 |
默認 |
類型 |
描述 |
status |
否 |
|
String |
如果設置此參數,一個IteratorStatus的實例將會壓入每個遍歷的堆棧 |
value |
否 |
|
Object/String |
要遍歷的可枚舉的(iteratable)數據源,或者將放入新列表(List)的對象 |
id |
否 |
|
Object/String |
用來標識元素的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元素用于獲得當前iterator的值 2、status被設成stuts,在iterator的里面就可以通過#stuts取得IteratorStatus的對象。IteratorStatus類包含當前序號信息,如是否第一個或最后一個,是否為奇數序號。這些信息在我們做格式化的時候,顯得非常有用。 --> <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標志訪問任何資源包的信息,而不只當前action相關聯的資源包。
參數:
名稱 |
必需 |
默認 |
類型 |
描述 |
value |
是 |
|
Object/String |
資源包的類路徑(如com.xxxx.resources.AppMsg) |
id |
否 |
|
Object/String |
用來標識元素的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
描述: 包含一個servlet的輸出(servlet或jsp的頁面)。
參數:
名稱 |
必需 |
默認 |
類型 |
描述 |
value |
是 |
|
String |
要包含的jsp或servlet |
id |
否 |
|
Object/String |
用來標識元素的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
描述: 為其他標簽提供參數,比如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和表單中為HTML的id屬性 |
例子: 請參考例4。
- set
描述: set標簽賦予變量一個特定范圍內的值。當希望給一個變量賦一個復雜的表達式,每次訪問該變量而不是復雜的表達式時用到。其在兩種情況下非常有用: 復雜的表達式很耗時 (性能提升) 或者很難理解 (代碼可讀性提高)。
參數:
名稱 |
必需 |
默認 |
類型 |
描述 |
name |
是 |
|
String |
變量名字 |
scope |
否 |
|
String |
變量作用域,可以為application, session, request, page, 或action. |
value |
否 |
|
Object/String |
將會賦給變量的值 |
id |
否 |
|
Object/String |
用來標識元素的id。在UI和表單中為HTML的id屬性 |
例子: 請參考例1。
- text
描述: 支持國際化信息的標簽。國際化信息必須放在一個和當前action同名的resource bundle中,如果沒有找到相應message,tag body將被當作默認message,如果沒有tag body,message的name會被作為默認message。
參數:
名稱 |
必需 |
默認 |
類型 |
描述 |
name |
是 |
|
String |
資源屬性的名字 |
id |
否 |
|
Object/String |
用來標識元素的id。在UI和表單中為HTML的id屬性 |
例子: 請參考例3。
- url
描述: 該標簽用于創建url,可以通過"param"標簽提供request參數。
 |
當includeParams的值時'all'或者'get', param標簽中定義的參數將有優先權,也就是說其會覆蓋其他同名參數的值。 |
參數: 略
例子:
<%@ 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沒提供,默認為堆棧頂端的元素。
參數:
名稱 |
必需 |
默認 |
類型 |
描述 |
default |
否 |
|
String |
如果屬性是null則顯示的default值 |
escape |
否 |
true |
Booelean |
是否escape HTML |
value |
否 |
棧頂 |
Object |
要顯示的值 |
id |
否 |
|
Object/String |
用來標識元素的id。在UI和表單中為HTML的id屬性 |
例子: 請參考例2。
- UI標志
UI標志又可以分為表單UI和非表單UI兩部分。表單UI部分基本與Struts 1.x相同,都是對HTML表單元素的包裝。不過,Struts 2.0加了幾個我們經常在項目中用到的控件如:datepicker、doubleselect、timepicker、optiontransferselect等。因為這些標志很多都經常用到,而且參數也很多,要在一篇文章詳細說明并非易事。
在此,我雖然不能夠詳細講述這些標志,但是可以與大家分享一個來Struts 2.0 Show Case一個例子。
 /**//*
* $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) 評論(21) 編輯 收藏 引用 所屬分類: Struts 2.0系列
|