JSTREE从后台取得数据并形成树

显示树型的页面:

	<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;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值