[Spring] jsTree 예제

개발자·2021년 8월 25일
post-thumbnail

소스 코드

Controller

@Controller
public class HomeController {
	private CompanyService companyService;
    
	@RequestMapping(value="/tree.do",method={RequestMethod.GET, RequestMethod.POST}) 
	public ModelAndView tree(ModelAndView mav) {
		mav.setViewName("tree");
		return mav;
	}

	@RequestMapping(value="/treelist.do",method= {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody 
	public List<CompanyModel> jqCompanyTree(CompanyModel vo,  Model model) throws Exception {
		List<CompanyModel> dataList = companyService.getCompanyTree();
		return dataList;
	}
}

Service

@Service
public class CompanyService {
	@Autowired
	private CompanyMapper mapper;

	public List<CompanyModel> getCompanyTree() {
		return mapper.getCompanyTree();
	}
}

mapper.java

@Repository
@Mapper
public interface CompanyMapper {

	List<CompanyModel> getCompanyTree();
}

mapper.xml

  • MYSQL에서 재귀 함수(RECURSIVE)를 통해 계층 구조의 데이터를 조회할 수 있다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.my.hello.mapper.CompanyMapper">
	<select id="getCompanyTree" resultType="CompanyModel">
		WITH RECURSIVE CTE (id, name, depth, parent_id) AS
		(
			SELECT t1.id, t1.name, t1.depth, t1.parent_id
			FROM tree_test t1
			WHERE t1.parent_id = '#'
		
			UNION ALL
		
			SELECT t2.id, t2.name, t2.depth, t2.parent_id
			FROM tree_test t2
			INNER JOIN CTE ON t2.parent_id = CTE.id
		)
		
		SELECT CTE.id, CTE.name, CTE.depth, CTE.parent_id FROM CTE
		ORDER BY CTE.id;
	</select>
</mapper>

Model(DTO)

  • lombok 사용
@Getter
@Setter
public class CompanyModel {
	private String id;
	private String name;
	private int depth;
	private String parent_id;
}

view(jsp)

  • ajax로 데이터를 가져와 트리를 생성한다.
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>User List</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />

    <script type="text/javascript" src="resources/js/jquery-3.4.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
   
    <script type="text/javascript">

    function getJson() {
	$.ajax({
            type:'get',
            url:'/treelist.do',
            dataType:'json',
            success: function(data) {
                var company = new Array();
                        // 데이터 받아옴
                $.each(data, function(idx, item){
                        company[idx] = {id:item.id, parent:item.parent_id, text:item.name};
                });

                        // 트리 생성
                $('#tree').jstree({
                    core: {
                                    data: company    //데이터 연결
                        },
                        types: {
                               'default': {
                                    'icon': 'jstree-folder'
                                }
                        },
                        plugins: ['wholerow', 'types']
                 })
                 .bind('loaded.jstree', function(event, data){
                        //트리 로딩 롼료 이벤트
                 })
                 .bind('select_node.jstree', function(event, data){
                       //노드 선택 이벤트
                 })

            },
            error:function (data) {
                alert("에러");
            }
       });
    }
    
    $(document).ready(function(){
    	getJson();
    });


    </script>
</head>
<body>
    <div id="tree"></div>
</body>
</html>


결과

화면

Database


Ref

profile
log.info("공부 기록 블로9")

0개의 댓글