Struts2學習——拓展:struts標籤庫
阿新 • • 發佈:2018-12-09
-
先將資料存到ActionContext中,然後再jsp中通過struts-tags標籤庫中的標籤獲取並顯示資料
資料準備:
@Override public String execute() throws Exception { List<String> list=new ArrayList<String>(); list.add("aaa"); list.add("bbb"); list.add("ccc"); ActionContext.getContext().put("list", list); Map<String, String> map=new HashMap<>(); map.put("name", "huhu"); map.put("age", "18"); map.put("gender", "男"); map.put("cool", "cool"); ActionContext.getContext().put("map", map); return "list"; }
jsp中使用的標籤:
<h1>struts標籤演示</h1> <s:property /><br> <s:iterator value="#list"> <s:property /><br> </s:iterator> <s:iterator value="map" var="m"> <s:property /><br> </s:iterator> <s:property value=""/><br> <s:iterator begin="1" end="10" status="a"> <s:property/>|<s:property value="#a.count"/><br> </s:iterator> <s:property value="#list.size()"/> <s:if test="#list.size()==2"> <s:property value="#list.size()"/> </s:if> <s:else> <s:property value="#map.size()"/> </s:else>
頁面顯示內容:
可見,標籤效果
-
<s:property />標籤預設獲取ActionContext棧頂的資料並返回該資料,StrutsAction就是我建立的Action類的類名,顯然這個標籤獲取到了此Action類的例項物件。
-
<s:iterator value="#list">可以任務是迴圈標籤,value可以使用ognl表示式語言獲取資料,然後改標籤對這個資料進行迴圈(如果可迴圈),然後迴圈體內使用<s:property />就可以直接獲得本次迴圈的資料
-
<s:if test="#list.size()==2">
-
<s:iterator begin="1" end="10" status="a">
<s:property/>|<s:property value="#a.count"/><br>
</s:iterator> 同樣為迴圈,可以理解為數字迴圈,begin為開始的值,end為結束的值,status是一個資訊記錄物件,本例中,每次迴圈會建立一個名a的物件,用於記錄本次迴圈 的資訊,使用"#a.count"可以獲取本次迴圈是第幾次迴圈,此式仍然為ognl表示式。
struts標籤庫不僅有這些資料控制標籤,還有表單標籤等。表單標籤,就是可以使用此標籤建立表單,知識寫法上不同,最後在頁面顯示仍然是翻譯為form表單來實現。
其中不得不說的就是ognl表示式的使用很頻繁。ognl表示式語言是十分強大的。Struts2框架中的資料傳輸基本都是使用ognl來完成的,所以Struts2框架也自帶ognl的jar包,學好ognl表示式,對Struts2框架的理解十分有好處。。。。。。