【JAVA】学习记录【递归查询子节点】

【JAVA】记录一下今天遇到的问题和解决方法

需求:1、后台树结构的数据,一个节点有一个唯一的key和若干children,每个子节点下又有若干子节点。要求通过key查询子节点列表。
2、因为数据是组装出来的,每次查询时组装一遍效率低,所以要求首次查询后把数据放到session中,然后通过递归查询session中的数据。

解决办法
1、查询的数据放入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、递归查询
之前想的办法是递归方法中,查询到key后直接 return children,但是方法一定要有返回值的话,遇到children为空也会返回null,整个递归就终止了。所以,新建一个全局变量用于接收查询的到的数据,这样就能保证数据全部遍历一遍。

	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);
                }
            }
        }
    }
发布了14 篇原创文章 · 获赞 1 · 访问量 262

猜你喜欢

转载自blog.csdn.net/qq_39938236/article/details/103200222