[JAVA] [recursive queries learning record sub-node]

[JAVA] the record about problems and solutions encountered today

Demand : 1, the background data tree structure, a node has a unique key and a plurality of Children, at each child node have a plurality of child nodes. Required by key query the list of children.
2, because the data is assembled out of every assembly query again inefficient, so the data required for the first time after the inquiry into the session, and then byRecursionQuery data in the session.

Solution :
1, data query into session

    public void initData() {
        List<TreeNodeDto> locationTree = this.getLocationTree(null); // 首次获取节点树的方法
        HttpSession session = HttpSessionHelper.getSession();
        session.setAttribute("tree", locationTree);
    }

HttpSessionHelper.getSession()方法

    public static HttpSession getSession() {
        HttpServletRequest request = getHttpServletRequest();
        if (request == null) {
            return null;
        }
        HttpSession session = request.getSession();
        return session;
    }
    
    public static HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes request = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (request == null || request.getRequest() == null) {
            return null;
        }
        HttpServletRequest httpServletRequest = request.getRequest();
        return httpServletRequest;
    }

2, recursive queries
to think before approach is recursive method, the query to the key directly after return children , but the method must have a return value, then met children is empty will return null, the entire recursion was terminated. So, create a new global variable is used to query the data received, so that we can ensure that all data traversing again.

	private List<TreeNodeDto> list;

	public List<TreeNodeDto> getChildLocation(String key) {
        HttpSession session = HttpSessionHelper.getSession();
        List<TreeNodeDto> tree = (List<TreeNodeDto>) session.getAttribute("locationTree"); // 获取session中的数据
        TreeNodeDto dto = new TreeNodeDto();
        dto.setKey("0");
        dto.setChildren(tree);
        if (key == null || key.length() == 0) {
            return tree;
        } else {
            if (tree != null) {
               getChildren(dto, key);
            }
        }
        return list;
    }

    public void getChildren(TreeNodeDto tree, String key) {
        if (key.equals(tree.getKey())) {
            list = tree.getChildren();
        } else {
            List<TreeNodeDto> children = tree.getChildren();
            if (children != null) {
                for (TreeNodeDto child : children) {
                    getChildren(child, key);
                }
            }
        }
    }
Published 14 original articles · won praise 1 · views 262

Guess you like

Origin blog.csdn.net/qq_39938236/article/details/103200222