显示树型的页面:
<script type="text/javascript">
$(document).ready(function(){
$("#documentCatalog").tree({
data:{
type: "json",
async: true,
opts:{
method: "POST",
url: "http://localhost:8088/oa/DocumentCatalog/documentCatalogTree.action?type=${param.type}&parentId=-1"
}
},
ui:{
dots : true, // BOOL - dots or no dots
theme_name : "default"// if set to false no theme will be loaded
}
}
);
});
</script>
struts.xml中相应的Action的配置:
<action name="documentCatalogTree" class="documentCatalogTree"> <!-- 不用设置result,直接用PrintWriter输出JSON型的数据 --> </action>
封装JSTREE使用的JSON数据的类
public class CatalogTree {
private String data;
private String state;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
action中的方法:
配置Tree的action:
因为action返回的是树的页面,所以Action应该给页面传递JSON数据
可以使用JSON的struts插件来解决,但处理起来不太好
使用以下方式:
在execute方法中return null,这样struts就不会到struts.xml中找相应的result了而是调用方法返回一个printWriter的数据,
且在返回之前把这个数据封闭成JSON的格式
数据的封装:
返回值一定要注意必须严格符合JSON的格式
有两个方法:一是使用字符串拼接的方式来封装,二是使用一个JSON的工具www.json.org里下载google-gson
使用前者太麻烦且容易出错
@Override
public String execute() throws Exception {
List<DocumentCatalog> catalogs = service.getDocumentCatalogs(type, parentId);
List<CatalogTree> trees = new ArrayList<CatalogTree>();
for(DocumentCatalog catalog : catalogs){
CatalogTree tree = new CatalogTree();
tree.setData(catalog.getName());
tree.setState("closed");
trees.add(tree);
}
Gson gson = new Gson();
String json = gson.toJson(trees);
HttpServletResponse response = ServletActionContext.getResponse();
//在取得out对象之前必须先进行设置
response.setContentType("text/json");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.write(json);
out.flush();
return null;
}