java - 使用 json 数据创建动态 TreeView - jsp 中的 dynatree

标签 java json jsp spring-mvc dynatree

我在数据库中有一个像这样的表:

id   -   title   -  parentID
-----------------------------
1        Root          null
2        item 1        1
3        item 2        1
4        item 3        1
5        item 3.1      4

这应该创建这样的东西:

--Root
----item 1
----item 2
----item 3
-------item 3.1

这是我的 Controller ,用于获取根节点及其子节点:

@RequestMapping(value="/CourtBranch/LoadTreeView", method = RequestMethod.GET)
    public void LoadList(@RequestParam("ParentId") String parentID,HttpServletRequest req, HttpServletResponse resp) {
        List lst;
        if (parentID.equals("Root"))
        {
            lst = _COURTBRANCH.LoadTreeChildren(null, "Root");   // selects records which have parent=null
        }
        else
        {
            lst = _COURTBRANCH.LoadTreeChildren(parentID, "TreeNode");   // selects records which have parent=parentID
        }

        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        try {
            resp.getWriter().print(_gson.toJson(lst));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

这个脚本加载我的根目录:

<script type="text/javascript">
  $(function(){
    $("#tree").dynatree({
          initAjax: {
              url: "/CourtBranch/LoadTreeView.json?ParentId=Root",
              data: { mode: "funnyMode" }
              },
      onActivate: function(node) {
        $("#echoActive").text(node.data.title);
      },
      onDeactivate: function(node) {
        $("#echoActive").text("-");
      }
    });
  });
</script>

现在我需要知道如何将 root 的 id 发送到我的 Controller 以获取 root 的子级 并将它们添加到根节点。 我应该使用appendAjax函数吗?怎么办?

最佳答案

基本上,您并不想直接在 Controller 中执行此操作。 (松耦合)

我会创建 2 个 utils 类 Tree<T>Node<T>管理您的树和节点:

这是树类:

public class Tree<T> {

    private Node<T> rootElement;

    public Tree() {
        super();
    }

    public Node<T> getRootElement() {
        return this.rootElement;
    }

    public void setRootElement(final Node<T> rootElement) {
        this.rootElement = rootElement;
    }

    public List<Node<T>> toList() {
        final List<Node<T>> list = new ArrayList<Node<T>>();
        walk(this.rootElement, list);
        return list;
    }

    private void walk(final Node<T> element, final List<Node<T>> list) {
        list.add(element);
        for (final Node<T> data : element.getChildren()) {
            walk(data, list);
        }
    }
}

以及带有一些辅助方法的节点类

public class Node<T> {

    private T data;
    private List<Node<T>> children;

    public Node() {
        super();
    }

    public Node(final T data) {
        this();
        setData(data);
    }

    public Boolean hasChildren() {
        return this.children.size() != 0;
    }

    public List<Node<T>> getChildren() {
        if (this.children == null) {
            return new ArrayList<Node<T>>();
        }
        return this.children;
    }

    public void setChildren(final List<Node<T>> children) {
        this.children = children;
    }

    public int getNumberOfChildren() {
        return this.children.size();
    }

    public void addChild(final Node<T> child) {
        if (this.children == null) {
            this.children = new ArrayList<Node<T>>();
        }
        this.children.add(child);
    }

    public void insertChildAt(final int index, final Node<T> child) throws IndexOutOfBoundsException {
        if (index == getNumberOfChildren()) {
            addChild(child);
            return;
        } else {
            this.children.get(index);
            this.children.add(index, child);
        }
    }

    public void removeChildAt(final int index) throws IndexOutOfBoundsException {
        this.children.remove(index);
    }

    public T getData() {
        return this.data;
    }

    public void setData(final T data) {
        this.data = data;
    }
}

然后我会让你的树类型扩展树。基于您的 Controller CourtBranch

假设您的 CourtBranch 模型具有以下结构(我使用 hibernate + jpa):

@Entity
@Table
public class CourtBranch

private String id;
private String name;
private Long partentId;

//getters setters etc...

创建一个扩展树的类:

public class CourtBranchTree extends Tree<CourtBranch>
    public CourtBranchTree{
        super();
    }

现在创建您的 TreeGridResponse 类:

public class TreeGridResponse {
    //inject the service to get the id of your model
    @Resource
    CourtBranchService cbService;
    //if you are using a repository for the db queries:
    @Resource
    CourtBranchRepository cbRepo;

    public TreeGridResponse(){
    }

    //returning the tree as a JSON to use AJAX
    public String cbBTreeAsJson(final CourtBranchTree tree){
        final StringBuffer sb = new StringBuffer();
        final CourtBranch root = tree.getRootElement().getData();
        sb.append("[\r {\"title\": \"" + root.getName() + "\", \"key\": \"" + root.getId() + "\", \"children\": [\r");
        final List<Node<CourtBranch>> children = tree.getRootElement().getChildren();
        loopforChildre(sb, children);
        sb.append("]");
        return sb.toString();
    }

    private StringBuffer loopForChildren(final StringBuffer sb, final List<Node<UserRight>> children) {
        for (int i = 0; i < children.size(); i++) {
            final Node<courtBranch> childElement = children.get(i);
            if (i == 0) {
                sb.append("{\"title\": \"" + childElement.getData().getName() + "\", \"key\": \"" + childElement.getData().getId() + "\"");
            } else {
                sb.append(", {\"title\": \"" + childElement.getData().getName() + "\", \"key\": \"" + childElement.getData().getId() + "\"");
            }
            if (childElement.hasChildren()) {
                sb.append(", \"children\": [\r");
                loopForChildren(sb, childElement.getChildren());
            } else {
                sb.append("}");
            }
        }
        sb.append("]}");
        return sb;
    }

    public CourtBranchTree get() {
        final CourtBranchTreetree tree = new CourtBranchTree();
        final Node<CourtBranch> root = new Node<CourtBranch> (this.cbRepo.findOne(Long.valueOf(1)));//gets your root
        getRecursive(root, tree);
        tree.setRootElement(root);
        return tree;
    }

    private void getRecursive(final Node<CourtBranch> courtBranch, final CourtBranchTree tree) {
        final List<CourtBranch> children = this.cbService.findCourtBranchByParentId(courtBranch.getData().getId());
        final List<Node<CourtBranch>> childElements = new ArrayList<Node<CourtBranch>>();
        for (final CourtBranch childCourtBranch : children) {
            final Node<CourtBranch> childElement = new Node<CourtBranch>(childUserRight);
            childElements.add(childElement);
            getRecursive(childElement, tree);
        }
        courtBranch.setChildren(childElements);
    }
}

在您的配置中注册 TreeGridResponse 以获取 bean 并将其注入(inject)到您的 Controller 中。

@Controller
public class CBController

@Resource
private TreeGridResponse gridResponse;

@RequestMapping(value="/CourtBranch/LoadTreeView", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String cbTree() {
    return this.gridResponse.cbBTreeAsJson(this.gridResponse.get());
}

注意 @ResponseBody 注释,它将指示 Spring 将您的字符串解析为 JSON,以便您的 AJAX 可以读取它。

还有你的jsp:

<div id ="cbTree"></div>
<script type ="text/javascript">
    $(function(){
    $("#cbTree").dynatree({
        initAjax:{
            url: /CourtBranch/LoadTreeView
            },
        checkbox: true,
        selectMode: 3
    });
    });
</script>

希望这有帮助...

关于java - 使用 json 数据创建动态 TreeView - jsp 中的 dynatree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19076772/

相关文章:

java - 每个文件的增量

java - 在电话上运行 tess-two

java - Apache Tomcat 应用程序中的相对文件路径引用

mysql - 无法使用 JSON_EXTRACT 在 MySQL 中提取具有特殊字符的键

java - Genson 1.4 (JSON) 不处理继承的 Pojo 的

Java常见的Try/Finally block 围绕不同的代码块 - 代码风格

javascript - 无法第二次读取json文件: "Unexpected end of input error"

jquery - Spring Mvc jsp页面在使用js和css文件初始化日历后给出空白输出

java - GCM 推送通知不起作用,并且注册 ID 也不显示

spring - 如何使用spring处理后退浏览器按钮问题?