package com.gtercn.ecard.action.organization;
import java.util.List;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.gtercn.ecard.bean.vo.OrganizationVO;
import com.gtercn.ecard.common.BaseAction;
import com.gtercn.ecard.service.organization.OrgService;
import com.gtercn.ecard.util.JsonMetaData;
@Controller
public class ShowOrgAction extends BaseAction {
private static final long serialVersionUID = 1L;
//result为异步返回页面的结果
private JSONObject result;
@Autowired
private OrgService orgService;
//Json工具类(自定义)
@Autowired
JsonMetaData jsonUtil;
@Override
public String execute() throws Exception {
jsonUtil = new JsonMetaData();
List<OrganizationVO> fistNodes = orgService.getFirstNode();
this.setResult(JsonMetaData.getJsonResult(fistNodes));
return SUCCESS;
}
//struts默认把具有get方式的数据域传回回调函数中
public JSONObject getResult() {
return result;
}
}
package com.gtercn.ecard.util;
import java.util.List;
import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.PropertyFilter;
import org.springframework.stereotype.Controller;
import com.gtercn.ecard.bean.organization.Organization; import com.gtercn.ecard.bean.vo.OrganizationVO;
/** * json 工具类 * * @author gtercn_hpf * */ @Controller public class JsonMetaData { /** * 得到一个json数组 * * @param fistNodes * @return */ public static JSONObject getJsonResult(List<OrganizationVO> fistNodes) {
JsonConfig jsonConfig = new JsonConfig();
JSONObject json = new JSONObject();
json.put("data", JSONArray.fromObject(fistNodes, jsonConfig)); return json;
}
public static JSONObject getSubNodeJson(List<Organization> nodes) { JsonConfig jsonConfig = new JsonConfig();
JSONObject json = new JSONObject();
//字段过滤器
jsonConfig.setJsonPropertyFilter(new PropertyFilter() { @Override public boolean apply(Object source, String name, Object value) { System.out.println(name); if (source != null) { if (name.equals("orgTitles") || name.equals("persons")) { return true; } } return false; } });
json.put("data", JSONArray.fromObject(nodes, jsonConfig)); return json; } }
页面ajax代码
function showOrg(){ $.ajax({ type:"POST", url:"showOrg.action", success:function(msg){
//默认返回的为字符串,需要把字符串转化为json对象 var backMsg=eval("("+msg+")"); var tree=backMsg.result.data; var zNodes=[]; for(var i=0;i<tree.length;i++){ var c = {"id":tree[i]["id"],"pId":tree[i]["pId"],"name":tree[i]["name"],"open":true,"click":"showChildrenNodes('"+tree[i]["id"]+"');"}; zNodes.push(c); } $.fn.zTree.init($("#treeDemo"), setting,zNodes); } }); }
时间有限就先记录这些把。。。 把javabean转化为json时会碰到hibernate的懒加载问题,可以opensessioninvew 这样懒加载的时候session不会关闭,再就是过滤掉乱连字段,注意大小写问题!!!!!