struts2.0的標籤庫(簡介)
用過struts1.x的人都知道,標籤庫有html、bean、logic、tiles,
而struts2.0裏的標籤卻沒有分類,只用在jsp頭文件加上
<%@ taglib prefix="s" uri="/struts-tags" %>
就能使用struts2.0的標籤庫
下面就介紹下每個標籤的用法(有錯請指正):
A:
<s:a href=""></s:a>-----超鏈接,類似於html裏的<a></a>
<s:action ></s:action>-----執行一個view裏面的一個action
<s:actionerror/>-----如果action的errors有值那麼顯示出來
<s:actionmessage/>-----如果action的message有值那麼顯示出來
<s:append></s:append>-----添加一個值到list,類似於list.add();
<s:autocompleter></s:autocompleter>-----自動完成<s:combobox>標籤的內容,這個是ajax
B:
<s:bean ></s:bean>-----類似於struts1.x中的,JavaBean的值
C:
<s:checkbox></s:checkbox>-----複選框
<s:checkboxlist list=""></s:checkboxlist>-----多選框
<s:combobox list=""></s:combobox>-----下拉框
<s:component></s:component>-----圖像符號
D:
<s:date/>-----獲取日期格式
<s:datetimepicker></s:datetimepicker>-----日期輸入框
<s:debug></s:debug>-----顯示錯誤信息
<s:div></s:div>-----表示一個塊,類似於html的<div></div>
<s:doubleselect list="" doubleName="" doubleList=""></s:doubleselect>-----雙下拉框
E:
<s:if test=""></s:if>
<s:elseif test=""></s:elseif>
<s:else></s:else>-----這3個標籤一起使用,表示條件判斷
F:
<s:fielderror></s:fielderror>-----顯示文件錯誤信息
<s:file></s:file>-----文件上傳
<s:form action=""></s:form>-----獲取相應form的值
G:
<s:generator separator="" val=""></s:generator>----和<s:iterator>標籤一起使用
H:
<s:head/>-----在<head></head>裏使用,表示頭文件結束
<s:hidden></s:hidden>-----隱藏值
I:
<s:i18n ></s:i18n>-----加載資源包到值堆棧
<s:include value=""></s:include>-----包含一個輸出,servlet或jsp頁面
<s:inputtransferselect list=""></s:inputtransferselect>-----獲取form的一個輸入
<s:iterator></s:iterator>-----用於遍歷集合
L:
<s:label></s:label>-----只讀的標籤
M:
<s:merge></s:merge>-----合併遍歷集合出來的值
O:
<s:optgroup></s:optgroup>-----獲取標籤組
<s:optiontransferselect doubleList="" list="" doubleName=""></s:optiontransferselect>-----左右選擇框
P:
<s:param></s:param>-----爲其他標籤提供參數
<s:password></s:password>-----密碼輸入框
<s:property/>-----得到'value'的屬性
<s:push value=""></s:push>-----value的值push到棧中,從而使property標籤的能夠獲取value的屬性
R:
<s:radio list=""></s:radio>-----單選按鈕
<s:reset></s:reset>-----重置按鈕
S:
<s:select list=""></s:select>-----單選框
<s:set ></s:set>-----賦予變量一個特定範圍內的值
<s:sort comparator=""></s:sort>-----通過屬性給list分類
<s:submit></s:submit>-----提交按鈕
<s:subset></s:subset>-----爲遍歷集合輸出子集
T:
<s:tabbedPanel ></s:tabbedPanel>-----表格框
<s:table></s:table>-----表格
<s:text ></s:text>-----I18n文本信息
<s:textarea></s:textarea>-----文本域輸入框
<s:textfield></s:textfield>-----文本輸入框
<s:token></s:token>-----攔截器
<s:tree></s:tree>-----樹
<s:treenode label=""></s:treenode>-----樹的結構
U:
<s:updownselect list=""></s:updownselect>-----多選擇框
<s:url></s:url>-----創建url
struts1.x標籤庫 (收藏)struts標籤庫
一.html標籤
1.html元素的標籤:
a1.<html:link forward="index"> 鏈接<global-forwards>中的name </html:link>
a2. <html:link href="http://www.baidu.com" > 鏈接到站點外 </html:link>
a3. <html:link page="/HtmlBasic.do">同一個應用 </html:link>
如:包含請求參數: <html:link page="/HtmlBasic.do?prop1=abc&prop2=123" />
包含單個請求變量:<% String stringBean = "Value to Pass on URL";
pageContext.setAttribute("stringBean", stringBean);%>
<html:link page="/HtmlBasic.do" paramId="urlParamName" paramName="stringBean" />
<jsp:useBean scope="page" />
<jsp:setProperty property="name" value="weiqin" /> //要有範圍
<html:link page="/Html" paramId="url" paramName="javaBean" paramProperty="name"/>
包含多個請求變量: <% java.util.HashMap myMap = new java.util.HashMap();
myMap.put("myString", new String("myStringValue") );
myMap.put("myArray", new String[] { "str1", "str2", "str3" });
pageContext.setAttribute("map", myMap);%>
<html:link page="/HtmlBasic.do" > url </html:link>
b.<html:img>: <html:img page="/struts-power.gif" /> //也可以包含單個或多個請求變量
<html:img src="/struts-power.gif" paramId="urlParamName" paramName="stringBean" />
<html:img page="/struts-power.gif" />
2.基本表單標籤:<html:form>,<html:text>,<html:hidden>,<html:submit>,<html:reset>
<html:cancel>Cancel</html:cancel> :Action中的取消事件:
FormBasicForm fbf = (FormBasicForm) form;
if (isCancelled(request)) { fbf.setStatus("Cancel was pressed!");
return (mapping.findForward("success")); }//表示取消選中
else { fbf.setStatus("Submit was pressed!");
return (mapping.findForward("success")); }
3.下拉列表和多選列表
<html:select property="colors" size="6" multiple="true" > // multiple下拉可多選
<html:option value="htmlselect.orange">Orange</html:option> //基本的頁面輸入
<html:option value="red" bundle="htmlselect.Colors" key="red"/>//從資源文件中顯示
<% Vector colorCollection = new Vector(); colorCollection.add(
new org.apache.struts.util.LabelValueBean("Pink", "htmlselect.pink"));
colorCollection.add( // Pink爲label htmlselect.pink爲value
new org.apache.struts.util.LabelValueBean("Brown", "htmlselect.brown"));
pageContext.setAttribute("colorCollection", colorCollection); %>
<html:options collection="colorCollection" property="value" //實際值
labelProperty="label" /> </html:select>// labelProperty顯示值
4.顯示錯誤消息: errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("key") );
a.顯示全局:<html:errors property="org.apache.struts.action.GLOBAL_MESSAGE"/>
b.顯示特定字段: errors.add("checkbox1", new ActionMessage("error.checkbox"));
<html:errors property="checkbox1" bundle="HtmlErrors" /> //bundle資源文件
5.顯示信息<html:messages>:
a.<html:messages message=”true”/>//如果爲true則從全局中搜索
則:ActionMessages actionMessages=new ActionMessages();
actionMessages.add(ActionMessages.GLOBAL_MESSAGE,new ActionMessage(“key”));
saveMessages(request,actionMessages);
b.從一定的範圍中查找:<html:messages >
<bean:write /> </html:messages>
則:protected void saveMessages(HttpServletRequest request,ActionMessages messages){
...request.setAttribute(GLOBAL_MESSAGE_key,messages); }
二:Struts Bean標籤
1.訪問http請求信息和JSP對象
a. <bean:cookie value="firsttime"/> // value爲默認值
<% if (cookie.getValue().equals("firsttime")) {
Cookie c = new Cookie("cookiedemo", "Hi Linda!");
c.setComment("A test cookie");c.setMaxAge(3600);response.addCookie(c);} %>
輸出: <bean:write property="value"/>
b. <bean:header /> <bean:write />
c. <bean:page property="session"/>//檢索JSP範圍,隱含對象
<bean:write property="creationTime"/>
d. <bean:parameter value="noarg"/> // value爲默認值
<bean:write />
檢索多值:<bean:parameter multiple="yes" value="noarg"/>
通過鏈接傳遞參數:<html:link page="/this.jsp?testarg=123&testarg=456&testarg=789">
循環輸出:<% for (int i=0; i <arg2.length; i++) {out.write(arg2[i] + "<BR>");} %>
2.訪問WEB應用資源: <message-resources parameter="res" key="special" />
a. <bean:message key="hello" arg0="Linda" /> //默認資源文件中:hello=Hello,{0}
<% request.setAttribute("stringBean","hello"); SomeBean bean=new SomeBean();
bean.setName("hello"); request.setAttribute("someBean",bean); %>
通過變量名或javaBean得到key值再訪問資源文件:
<bean:message bundle="special" />// bundle不能省,只能訪問資源文件
<bean:message bundle="special" property="name"/>
b. <bean:include>同<jsp:include>,但將WEB資源存放在一個變量中,有forward,page,href
<bean:include page="/testpage1.jsp"/> <bean:write filter="false"/>
<bean:include forward="testpage2"/> <bean:write filter="false"/>
3.定義或輸出javaBean,bean:write標籤filter爲true時會將特殊符號轉換成普通字符串
a.value屬性:<bean:define value="lib"/><bean:write />
name和property屬性:<% request.setAttribute("sessionBean", session); %>
<bean:define property="servletContext"/>
// contextBean爲javax.servlet.ServletContext類型,實例化
<bean:write property="servletContextName"/>
name和type屬性(用於複製):<bean:define
type="javax.servlet.ServletContext"/>
<bean:write property="majorVersion"/>
三.Struts Logic標籤:
1.邏輯判斷:(greatEqual,lessEqual,greatThan...)
<% Cookie c = new Cookie("username", "Linda"); c.setComment("A test cookie");
c.setMaxAge(3600); response.addCookie(c); %>
a.<logic:equal cookie="username" value="Linda">UserName is Linda </logic:equal>
b. <% SomeBean bean=new SomeBean(); bean.setName("Linda");
request.setAttribute("someBean",bean);%>
<logic:notEqual property="name" value="Tom">not Tom </logic:notEqual>
c. <% request.setAttribute("number","100"); %>
<logic:lessThan value="100.0a" > "100" 小於"100.0a"</logic:lessThan >
2.字符串匹配:變量中是否包含指定的字符串
<% request.setAttribute("authorName", "LindaSun");%>
a.<logic:match scope="request" value="Linda">
<bean:write /> has the string 'Sun' in it.</logic:match>
<logic:notMatch scope="request" value="Linda" /> //還有end屬性
<logic:match scope="request" value="Linda" location="start">
<bean:write /> starts with the string 'Linda'.</logic:match>
3.判斷指定內容是否存在
<% ActionErrors errors = new ActionErrors();
errors.add("totallylost", new ActionMessage("application.totally.lost"));
request.setAttribute(Globals.ERROR_KEY, errors);
request.setAttribute("myerrors",errors);request.setAttribute("emptyString","");%>
a.<logic:empty > emptyString is empty! </logic:empty>
b.<logic:notPresent property="noSuchProperty">
判斷指定的安全角色,用戶,cookie,header或javaBean是否存在 </logic:notPresent>
c. <logic:messagesPresent >在範圍內檢索key</logic:messagesPresent>
<logic:messagesNotPresent message="true">
從Globals.MESSAGE_KEY中檢索,不同於Globals.ERROR_KEY </logic:messagesNotPresent>
<logic:messagesNotPresent property="noSuchError">
從指定的ActionMessages對象中檢索 </logic:messagesNotPresent>
4.請求轉發或重定向a.<logic:forward />,與配置中<global-forwards>同名
b.<logic:redirect href="http://www.apache.org"/>,也有page,href和forward三種屬性
5.循環遍歷//offset爲開始位置,indexId爲序號
a. 遍歷集合<% Vector animals=new Vector(); animals.addElement("Dog");
animals.addElement("Cat"); animals.addElement("Bird");
request.setAttribute("Animals", animals);%>
<logic:iterate indexId="index" offset="1" length="2">
<bean:write />.<bean:write /><BR></logic:iterate>
b. 遍歷Map<% HashMap h= new HashMap();String fruits[ ] = {"apple","orange","banana"};
h.put("Fruits", fruits); request.setAttribute("catalog", h); %>
<logic:iterate > <bean:write property="key"/><BR>
<logic:iterate property="value"><bean:write />
</logic:iterate> </logic:iterate> //如果value不是集合就不用嵌套了
四.利用Tiles模板和Tiles組件創建複合式網頁
1.在web.xml中配置所需要的<tablib>url和location
2.建立tiles的xml文件放在WEB-INF下:<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
<tiles-definitions> <definition path="/layout.jsp">
<put value="header.jsp"/>
<put value="indexContent.jsp"/>
<put value="footer.jsp"/> </definition>
<definition path="/layout.jsp">
<put value="sidebar.jsp"/>
<put value="header.jsp"/>
<put value="productContent.jsp"/>
<put value="footer.jsp"/> </definition>
</tiles-definitions>
3.在struts配置文件中配置TilesPlugin插件(ctrl+n):
<plug-in className="org.apache.struts.tiles.TilesPlugin" >
<set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml"/>
<set-property property="definitions-parser-validate" value="true"/> </plug-in>
4.在Action已經存在ActionServlet,並在struts配置文件中配置Action來調用Tiles組件
<action path="/index" type="org.apache.struts.actions.ForwardAction"
parameter="index-definition"> </action>
ForwardAction爲Action內置對象,專門負責轉發功能,在將請求轉發給parameter的組件
5.在index.jsp中插入Tiles組件<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>
<tiles:insert definition="index-definition"/>
6.在layout.jsp文件中進行佈局並設計好其他頁面:
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles"%>
<table width="100%" height="100%">
<tr><td height="15%"><tiles:insert attribute="header"/> </td> </tr>
<tr><td valign="top"><tiles:insert attribute="content"/> </td> </tr>
<tr><td valign="bottom"><tiles:insert attribute="footer"/></td></tr> </table>
備註:在需要出現的頁面只有寫<tiles:insert definition="*"/>就可以插入框架,根據definition中的content改變主體。
7.Tiles組件的組合(type="definition")以示區別
<tiles-definitions>
<definition path="/sidebar-layout.jsp">
<put value="flags.jsp"/> </definition>
<definition path="/layout.jsp">
<put value="sidebar-definition" type="definition"/>
<put value="header.jsp"/>
</definition> </tiles-definitions>//將一個組件put成另一個組件的元素