在上一篇文章《Struts 2與AJAX(第一部分)》,我已經簡單地介紹了<s:tree />的一些用法,接下來我將繼續(xù)深入講解<s:tree />的使用和通過DWR實現(xiàn)AJAX校驗。
更多<s:tree />
在Struts 2的showcase中有兩個<s:tree />的例子,分別是靜態(tài)樹與動態(tài)樹。所謂的靜態(tài)樹即是在編寫JSP代碼時通過<s:treenode />生成樹節(jié)點。我的上一篇文章的例子就是一個典型的靜態(tài)樹。而動態(tài)樹則是在程序運行期間,Struts 2 運行時(Runtime)根據程序中的數據動態(tài)創(chuàng)建樹節(jié)點。雖然在兩個例子中<s:tree />的theme屬性都為“ajax”,但是從嚴格意義上來說,這兩種樹都不屬于AJAX樹,因為它們都是在輸出頁面時將全部節(jié)點加載到其中,而不是在父節(jié)點展開時通過XHR(XMLHttpRequest)獲取節(jié)點數據。
動態(tài)樹
下面我們先看一下動態(tài)樹的例子,接著再一步步地將其改造為名副其實的AJAX 樹。下例將會把WEB應用程序的目錄樹展現(xiàn)在JSP頁面中。因此,我需要先包裝一下java.io.File 類,代碼如下:
package tutorial;
import java.io.File;
public class FileWrapper {
private File file;
public FileWrapper(String path) {
file = new File(path);
}
public FileWrapper(File file) {
this.file = file;
}
public String getId() {
return "file_" + file.hashCode();
}
public String getName() {
return file.getName();
}
public String getAbsolutePath() {
return file.getAbsolutePath();
}
public FileWrapper[] getChildren() {
File[] files = file.listFiles();
if(files != null && files.length > 0) {
int length = files.length;
FileWrapper[] wrappers = new FileWrapper[length];
for(int i = 0; i < length; ++i) {
wrappers[i] = new FileWrapper(files[i]);
}
return wrappers;
}
return new FileWrapper[0];
}
} 清單1 src/tutorial/FileWrapper.java之所以需要對File類進行如此包裝,是因為<s:tree />用于動態(tài)樹時,rootNode、nodeIdProperty、nodeTitleProperty 和 childCollectionProperty等屬性都必填的。
然后是Action類的代碼如下:
package tutorial;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
public class DynamicTreeAction extends ActionSupport implements ServletRequestAware {
private static final long serialVersionUID = 1128593047269036737L;
private HttpServletRequest request;
private FileWrapper root;
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public FileWrapper getRoot() {
return root;
}
@Override
public String execute() {
root = new FileWrapper(request.getSession().getServletContext().getRealPath("/"));
return SUCCESS;
}
} 清單2 src/tutorial/DynamicTreeAction.java上述代碼取得WEB應用程序的根目錄的絕對路徑后,初始化FileWrapper對象root。該對象將為JSP頁面的<s:tree />的根節(jié)點。如下代碼所示:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Struts 2 AJAX - More Tree</title>
<s:head theme="ajax" debug="true" />
<script type="text/javascript">
/* <![CDATA[ */
function treeNodeSelected(arg) {
alert(arg.source.title + ‘ selected‘);
}
function treeNodeExpanded(arg) {
alert(arg.source.title + ‘ expanded‘);
}
function treeNodeCollapsed(arg) {
alert(arg.source.title + ‘ collapsed‘);
}
dojo.addOnLoad(function() {
var t = dojo.widget.byId(‘appFiles‘);
dojo.event.topic.subscribe(t.eventNames.expand, treeNodeExpanded);
dojo.event.topic.subscribe(t.eventNames.collapse, treeNodeCollapsed);
var s = t.selector;
dojo.event.connect(s, ‘select‘, ‘treeNodeSelected‘);
});
/* ]]> */
</script>
</head>
<body>
<h2>
Dynamic Tree Example
</h2>
<div style="float:left; margin-right: 50px;">
<s:tree id="appFiles" theme="ajax" rootNode="root"
nodeTitleProperty="name" nodeIdProperty="id"
childCollectionProperty="children" />
</div>
</body>
</html>
清單3 WebContent/Tree.jsp因為<s:tree />的treeCollapsedTopic和treeExpandedTopic屬性都沒有起作用,所以如果我們想要監(jiān)聽這兩個事件,就必須使用上述代碼的方法。
最后是struts.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="Struts2_AJAX_DEMO" extends="struts-default">
<action name="DynamicTree" class="tutorial.DynamicTreeAction">
<result>Tree.jsp</result>
</action>
</package>
</struts>
清單4 src/struts.xml發(fā)布運行應用程序,在瀏覽器地址欄中鍵入http://localhost:8080/Struts2_Ajax2/DynamicTree.action,有如下圖所示頁面:
圖1 動態(tài)樹示例 AJAX 樹
正如我在文章開頭所說,Struts 2所提供的靜態(tài)樹和動態(tài)樹都不是嚴格意義上的AJAX樹。下面就讓我們來實現(xiàn)一個如假包換的AJAX樹。首先要說明的是,Struts 2的<s:tree />默認是不支持這種按需加載數據的AJAX樹。不過因為它是基于Dojo的樹控件(Widget)所以要擴展也很方便。
Dojo 通過名為“TreeRPCController”的控件實現(xiàn) AJAX 樹,它會監(jiān)聽被控制樹的事件。當發(fā)生展開節(jié)點的事件時,TreeRPCController就會向URL發(fā)送XHR請求,該URL由TreeRPCController的RPCUrl 屬性定義。XHR請求格式類似如下格式:
http://localhost:8080/Struts2_Ajax2/AjaxTree.action?action=getChildren&data={"node":{"widgetId":"file_226092423","objectId":"C:\\Program Files\\Tomcat 5.5\\webapps\\Struts2_Ajax2","index":0,"isFolder":true},"tree":{"widgetId":"appFiles","objectId":""}}&dojo.preventCache=1182913465392
清單5 XHR樣本顯而易見,請求中包含三個參數,分別是action為“getChildren”(固定值),data一個包含當前節(jié)點與樹信息的JSON串和dojo.preventCache隨機串,用于緩存不同節(jié)點的請求響應(父節(jié)點只會在第一次被展開時到服務器端加載數據,之后都是從瀏覽器的緩存中讀取數據,可以提高應用程序性能)。
首先我要先寫一個加載樹節(jié)點數據的Action類,代碼如下:
package tutorial;
import java.util.Map;
import com.googlecode.jsonplugin.JSONExeption;
import com.googlecode.jsonplugin.JSONUtil;
public class AjaxTreeAction extends DynamicTreeAction {
private static final long serialVersionUID = 3970019751740942311L;
private String action;
private String data;
private FileWrapper[] wrappers;
public void setAction(String action) {
this.action = action;
}
public void setData(String data) {
this.data = data;
}
public FileWrapper[] getWrappers() {
return wrappers;
}
@Override
public String execute() {
if("getChildren".equals(action)) {
try {
Object o = JSONUtil.deserialize(data);
String path = ((Map) ((Map) o).get("node")).get("objectId").toString();
wrappers = new FileWrapper(path).getChildren();
} catch (JSONExeption e) {
e.printStackTrace();
}
return "ajax";
}
return super.execute();
}
} 清單6 src/tutorial/AjaxTreeAction.java上述代碼可能需要解釋一下:
- action屬性對應于XHR中的action,如果它為“getChildren”時,則需要進行加載子節(jié)點操作。否則,會讀取樹的根節(jié)點,并返回JSP頁面;
- 通過上面XHR的分析,大家可以知道data是代表樹和當前節(jié)點的JSON串,故應將其反串行化為Map對象,并將其 objectId屬性取出。通常情況下,Dojo樹的objectId屬性代表服務器端的對象的標識,在本例中為文件夾的絕對路徑;
- wrappers屬性表示當前文件夾下的文件數組,它被傳送到Freemarker頁面,翻譯為Dojo樹節(jié)點數組的JSON串。
下面是Freemarker頁面的代碼:
[
<#list wrappers as r>
{ "title": "${r.name}", "isFolder": <#if r.children?size gt 0>true<#else>false</#if>, "id": "${r.id}", "objectId": "${r.absolutePath?js_string}" }<#if r_has_next>,</#if>
</#list>
]
清單7 WebContent/AjaxTree.ftl以上代碼中<#list></#lsit>的寫法是Freemarker中遍歷集合的寫法;而<#if r.children?size gt 0>判斷“r”對象的children屬性是否為空;r.absolutePath?js_string 就是將“r”的absolutePath屬性的值輸出為Javascript 的字串符形式;<#if r_has_next></#if>判斷集合是否有下一項數據。如果希望更詳細地了解Freemarker的使用,請參考該手冊。
接下來,讓我們看看Action的配置代碼片段:
<action name="AjaxTree" class="tutorial.AjaxTreeAction">
<result>AjaxTree.jsp</result>
<result name="ajax" type="freemarker">AjaxTree.ftl</result>
</action>
清單8 src/struts.xml配置片段最后是JSP頁面代碼:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Struts 2 AJAX - More Tree</title>
<s:head theme="ajax" debug="true" />
<script type="text/javascript">
/* <![CDATA[ */
function treeNodeSelected(arg) {
alert(arg.source.title + ‘ selected‘);
}
dojo.addOnLoad(function() {
var t = dojo.widget.byId(‘appFiles‘);
var s = t.selector;
dojo.event.connect(s, ‘select‘, ‘treeNodeSelected‘);
});
/* ]]> */
</script>
</head>
<body>
<h2>
AJAX Tree Example
</h2>
<div style="float:left; margin-right: 50px;">
<script type="text/javascript">
/* <![CDATA[ */
dojo.require("dojo.lang.*");
dojo.require("dojo.widget.*");
dojo.require("dojo.widget.Tree");
dojo.require("dojo.widget.TreeRPCController");
/* ]]> */
</script>
<div dojoType="TreeRPCController" widgetId="treeController"
DNDcontroller="create" RPCUrl="<s:url />"></div>
<div dojoType="Tree" widgetId="appFiles" toggle="fade" controller="treeController">
<div dojoType="TreeNode" title=‘<s:property value="root.name" />‘
widgetId=‘<s:property value="root.id" />‘
isFolder=‘<s:property value="root.children.length > 0" />‘
objectId=‘<s:property value="root.absolutePath" />‘>
</div>
</div>
</div>
</body>
</html>
清單9 WebContent/AjaxTree.jsp由于上面所提及的原因,我在上述的代碼中并沒有使用<s:tree />標志,而是使用了Dojo的寫法——創(chuàng)建 widgetId 為“treeController”的 TreeRPCController 并將設為樹的控制器。
發(fā)布運行應用程序,在瀏覽器地址欄中鍵入http://localhost:8080/Struts2_Ajax2/AjaxTree.action,點開某個節(jié)點,在節(jié)點加載的過程中,加號圖標變成時鐘狀圖標,如下圖所示頁面:
圖2 AJAX樹示例 自定義<s:tree />的AJAX的主題(theme)
Struts 2的標志過人之外在于它允許開發(fā)人員自定義標志的頁面輸出。要做到這一點,你所需要做的只是創(chuàng)建一個自定義的theme并將其應用到相應標志。下面就讓我自定義一個真正的AJAX的<s:tree/>的theme。
首先,你的源文件的根目錄下新建包“template.realajax”。
然后,在上一步所建的包中新建“tree.ftl”文件,內容如下:
<script type="text/javascript">
/* <![CDATA[ */
dojo.require("dojo.lang.*");
dojo.require("dojo.widget.*");
dojo.require("dojo.widget.Tree");
dojo.require("dojo.widget.TreeRPCController"); <#-- Added by Max -->
/* ]]> */
</script>
<#-- Added by Max -->
<div dojoType="TreeRPCController"
widgetId="${parameters.id?html}_controller"
DNDcontroller="create"
RPCUrl="<@s.url />">
</div>
<#-- End -->
<div dojoType="Tree"
<#if parameters.blankIconSrc?exists>
gridIconSrcT="<@s.url value=‘${parameters.blankIconSrc}‘ encode="false" includeParams=‘none‘/>"
</#if>
<#if parameters.gridIconSrcL?exists>
gridIconSrcL="<@s.url value=‘${parameters.gridIconSrcL}‘ encode="false" includeParams=‘none‘/>"
</#if>
<#if parameters.gridIconSrcV?exists>
gridIconSrcV="<@s.url value=‘${parameters.gridIconSrcV}‘ encode="false" includeParams=‘none‘/>"
</#if>
<#if parameters.gridIconSrcP?exists>
gridIconSrcP="<@s.url value=‘${parameters.gridIconSrcP}‘ encode="false" includeParams=‘none‘/>"
</#if>
<#if parameters.gridIconSrcC?exists>
gridIconSrcC="<@s.url value=‘${parameters.gridIconSrcC}‘ encode="false" includeParams=‘none‘/>"
</#if>
<#if parameters.gridIconSrcX?exists>
gridIconSrcX="<@s.url value=‘${parameters.gridIconSrcX}‘ encode="false" includeParams=‘none‘/>"
</#if>
<#if parameters.gridIconSrcY?exists>
gridIconSrcY="<@s.url value=‘${parameters.gridIconSrcY}‘ encode="false" includeParams=‘none‘/>"
</#if>
<#if parameters.gridIconSrcZ?exists>
gridIconSrcZ="<@s.url value=‘${parameters.gridIconSrcZ}‘ encode="false" includeParams=‘none‘/>"
</#if>
<#if parameters.expandIconSrcPlus?exists>
expandIconSrcPlus="<@s.url value=‘${parameters.expandIconSrcPlus}‘ includeParams=‘none‘/>"
</#if>
<#if parameters.expandIconSrcMinus?exists>
expandIconSrcMinus="<@s.url value=‘${parameters.expandIconSrcMinus?html}‘ includeParams=‘none‘/>"
</#if>
<#if parameters.iconWidth?exists>
iconWidth="<@s.url value=‘${parameters.iconWidth?html}‘ encode="false" includeParams=‘none‘/>"
</#if>
<#if parameters.iconHeight?exists>
iconHeight="<@s.url value=‘${parameters.iconHeight?html}‘ encode="false" includeParams=‘none‘/>"
</#if>
<#if parameters.toggleDuration?exists>
toggleDuration=${parameters.toggleDuration?c}
</#if>
<#if parameters.templateCssPath?exists>
templateCssPath="<@s.url value=‘${parameters.templateCssPath}‘ encode="false" includeParams=‘none‘/>"
</#if>
<#if parameters.showGrid?exists>
showGrid="${parameters.showGrid?default(true)?string}"
</#if>
<#if parameters.showRootGrid?exists>
showRootGrid="${parameters.showRootGrid?default(true)?string}"
</#if>
<#if parameters.id?exists>
id="${parameters.id?html}"
</#if>
<#if parameters.treeSelectedTopic?exists>
publishSelectionTopic="${parameters.treeSelectedTopic?html}"
</#if>
<#if parameters.treeExpandedTopic?exists>
publishExpandedTopic="${parameters.treeExpandedTopic?html}"
</#if>
<#if parameters.treeCollapsedTopic?exists>
publishCollapsedTopic="${parameters.treeCollapsedTopic?html}"
</#if>
<#if parameters.toggle?exists>
toggle="${parameters.toggle?html}"
</#if>
controller="${parameters.id?html}_controller" <#-- Added by Max -->
>
<#if parameters.label?exists>
<div dojoType="TreeNode" title="${parameters.label?html}"
<#if parameters.nodeIdProperty?exists>
id="${stack.findValue(parameters.nodeIdProperty)}"
<#else>
id="${parameters.id}_root"
</#if>
>
<#elseif parameters.rootNode?exists>
${stack.push(parameters.rootNode)}
<#-- Edited by Max -->
<div dojoType="TreeNode"
title="${stack.findValue(parameters.nodeTitleProperty)}"
widgetId="${stack.findValue(parameters.nodeIdProperty)}"
isFolder="<#if stack.findValue(parameters.childCollectionProperty)?size gt 0>true<#else>false</#if>"
objectId="${stack.findValue(parameters.nameValue)}">
</div>
<#-- End -->
<#assign oldNode = stack.pop()/> <#-- pop the node off of the stack, but don‘t show it -->
</#if>
清單10 src/template/realajax/tree.ftl對上述稍作解釋,上述代碼主要在原版的src/template/ajax/tree.ftl的基礎上添加了TreeRPCController的控件,并只輸出根節(jié)點。由于<s:tree />沒有類似nodeObjectIdProperty的屬性,所以我用了value屬性表示objectId對應的屬性名稱。
接著新建tree-close.ftl文件,內容和原版的一樣,如下所示:
<#if parameters.label?exists></div></#if></div>
清單11 src/template/realajax/tree-close.ftl再下來就應該是將theme應用到<s:tree />,如下代碼所示:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Struts 2 AJAX - More Tree</title>
<s:head theme="ajax" debug="true" />
<script type="text/javascript">
/* <![CDATA[ */
function treeNodeSelected(arg) {
alert(arg.source.title + ‘ selected‘);
}
dojo.addOnLoad(function() {
var t = dojo.widget.byId(‘appFiles‘);
var s = t.selector;
dojo.event.connect(s, ‘select‘, ‘treeNodeSelected‘);
});
/* ]]> */
</script>
</head>
<body>
<h2>
AJAX Tree Example
</h2>
<div style="float:left; margin-right: 50px;">
<s:tree id="appFiles" theme="realajax" rootNode="root"
nodeTitleProperty="name" nodeIdProperty="id"
childCollectionProperty="children" value="absolutePath" />
</div>
</body>
</html>
清單12 WebContent/AjaxTreeTheme.jsp上述代碼中<s:tree />的用法,除了theme改為“realajax”和多了value="absolutePath"外,幾乎和靜態(tài)樹中的一樣。
為了不影響前一個例子,我們?yōu)樵揓SP文件配置類型相同的Action,如下代碼所示:
<action name="AjaxTreeTheme" class="tutorial.AjaxTreeAction">
<result>AjaxTreeTheme.jsp</result>
<result name="ajax" type="freemarker">AjaxTree.ftl</result>
</action>
清單13 src/struts.xml配置片段發(fā)布運行應用程序,在瀏覽器地址欄中鍵入http://localhost:8080/Struts2_Ajax2/AjaxTreeTheme.action,結果如圖2所示。
總結
通過上述例子,大家知道Struts 2 的AJAX 標志是基于Dojo控件開發(fā)的,所以如果大家希望熟練地使用這些標志,最好去了解一下Dojo。
本來還打算介紹一下Struts 2與DWR,不過看看文章的篇幅似乎足夠自成一篇了,因此DWR相關的內容要留待下文繼續(xù)了。