在struts2中,tree的实现主要是通过struts2-dojo-plugin-XXX.jar中的tree标签来实现的,首先在项目中引入此包,我使用的是sturts2.1.8.1。
在JSP中使用<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>导入标签标签的同时,别忘了再HEAD标签中添加<sx:head/>,客户端JS文件的导入全指望它了!下面是实现tree的三种方式:
1.静态方式 也就是tree中的各个节点是在jsp文件中静态写入的,在运行之前就知道其结构,下面是一个Demo:

<h2>1.Three Without AJAX</h2>
<sx:tree label="Tree without AJAX" id="parentId"
templateCssPath="/struts/tree.css" showRootGrid="true"
showGrid="true">
<sx:treenode label="child1" id="child1Id">
<sx:treenode label="grandchild1" id="grandchild1Id"/>
<sx:treenode label="grandchild2" id="grandchild2Id"/>
<sx:treenode label="grandchild3" id="grandchild3Id"/>
<sx:treenode label="grandchild4" id="grandchild4Id"/>
<sx:treenode label="grandchild5" id="grandchild5Id"/>
</sx:treenode>
<sx:treenode label="child2" id="child2Id"/>
<sx:treenode label="child3" id="child3Id"/>
<sx:treenode label="child4" id="child4Id"/>
<sx:treenode label="child5" id="child5Id"/>
<sx:treenode label="child6" id="child6Id">
<sx:treenode label="gChild1" id="gChild1Id"/>
<sx:treenode label="gChild2" id="gChild2Id"/>
</sx:treenode>
<sx:treenode label="child7" id="child7Id"/>
</sx:tree>
效果图如上所示。
2.半动态方式 下面的例子是根据服务器端的项目目录生成的节点树,在jsp中的表现代码上显得非常简捷:
首先要生成一个用于封装目录下文件结构的类:FileWrapper.Class

package tree;
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;
}
else{
return new FileWrapper[0];
}
}
}
新建一个Action,用于向ValueStack中添加生成目录树所需的一些数据,

package tree;
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 = -8571025932301813496L;
private FileWrapper root;
private HttpServletRequest request;
public FileWrapper getRoot(){
return root;
}
public void setServletRequest(HttpServletRequest request){
this.request = request;
}
public String execute(){
root = new FileWrapper(request.getSession().getServletContext().getRealPath("/"));
return SUCCESS;
}
}
在xml中配置action

<package name="ajax" namespace="/ajax" extends="json-default">
<action name="DynamicTree" class="tree.DynamicTreeAction">
<result>/tree.jsp</result>
</action>
</package>
JSP文件内容:
<h2>2.Tree with AJAX</h2>
<sx:tree id="appFiles" rootNode="root"
nodeTitleProperty="name" nodeIdProperty="id"
childCollectionProperty="children"/>
看起来非常简捷,其实struts已经帮我们干了好多事情,
OK,查看一下效果: