본문 바로가기
개발/Spring

[SpringBoot] DataTable(JavaScript) - 적용하기

by 코딩하는 흰둥이 2024. 5. 5.
반응형

이전글 이어서

https://greed-yb.tistory.com/251

 

[SpringBoot] Thymeleaf - layout 적용하기

https://greed-yb.tistory.com/218#google_vignette [Spring] Bootstrap SB Admin 2 설치하기 https://greed-yb.tistory.com/209 [SpringBoot+IntelliJ+Oracle+Thymeleaf+Paging] 웹 게시판 만들기(1) - 구성 Java 17 Maven Spring Boot 3.0.3 Oracle 11g Intell

greed-yb.tistory.com

 

 

 

DataTable 이란?

jquery 라이브러리로 데이터를 테이블로 쉽게 그려주고 페이징 및 검색, 정렬, 엑셀 등의 기능이 모두 들어있다

BootStrap - /bootstrap/vendor/datatables/ 폴더 내에 같이 포함되어 있으며, 아래 사이트를 참고하길 바란다.

https://datatables.net/

 

DataTables | Javascript table library

DataTables Javascript table library Advanced tables, instantly DataTables is a Javascript HTML table enhancing library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTM

datatables.net

 

 

 

 

게시판 페이지(Board.html)
<!DOCTYPE html>
<html lang="ko"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"  layout:decorate="~{/layout/layout}">
<!-- Main Content -->
<th:block layout:fragment="content">

    <!-- Begin Page Content -->
    <div class="container-fluid">

        <!-- Page Heading -->
        <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">게시판</h1>
        </div>

        <!-- Content Row -->
        <div>
            <!-- DataTales Example -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">DataTables Example</h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered" id="board_dataTable" style="width: 98%">
                            <thead>
                            <tr>
                                <th>No</th>
                                <th>작성자</th>
                                <th>제목</th>
                                <th>내용</th>
                                <th>날짜</th>
                            </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

</th:block>
<!-- End of Main Content -->

<th:block layout:fragment="pagescript">
    <script th:src="@{/bootstrap/vendor/datatables/jquery.dataTables.min.js}"></script>
    <script th:src="@{/bootstrap/vendor/datatables/dataTables.bootstrap4.min.js}"></script>
    <script th:src="@{/bootstrap/js/Board.js}"></script>
</th:block>
</html>

 

이전글에 이어서 layout을 적용한 Board.html 파일을 만들어 게시판 페이지로 생성하였다

Bootstrap 에 있는 dataTable(table.html) 예제 파일을 가져와서 수정하였다

 

테이블 <tbody>의 데이터는 동적으로 생성하기 위해 <thead> 만 선언한다

<div> 태그의 class 들은 Bootstrap css 용이다

 

DataTable.js와 Board.js 를 사용하기 위해 선언한다

 

 

Board.js(DataTable 설정 옵션)
// ajax로 가져온 데이터 목록
let board_data = [];

// DataTable render
function boardInit(data){
    $("#board_dataTable").DataTable({
        data: data,                                                     // 가져온 데이터
        "paging": true,                                                 // 페이징
        "lengthMenu": [[10,30, 50, 100, -1], [10,30, 50, 100, "All"] ], // 목록 개수
        "pageLength": 10,                                               // 보여지는 기본 개수
        "searching": true,                                              // 검색 기능
        "info": true,                                                   // 정보 표시
        // "scrollX": false,                                            // 가로 스크롤(true , false)
        // "scrollY": false,                                            // 새로 스크롤(false , px 단위 : 200 )
        "ordering": true,                                               // 정렬 기능
        "order": [0 , "asc"],                                           // 정렬 기준
        "language": {                                                   // 언어 설정
            decimal:        "",
            emptyTable:     "검색된 데이터가 없습니다.",
            info:           "Showing _START_ to _END_ of _TOTAL_ entries",
            infoEmpty:      "Showing 0 to 0 of 0 entries",
            infoFiltered:   "(filtered from _MAX_ total entries)",
            infoPostFix:    "",
            thousands:      ",",
            lengthMenu:     " _MENU_ ",
            loadingRecords: "Loading...",
            processing:     "Processing...",
            search:         "Search",
            zeroRecords:    "항목이 존재하지 않습니다",
            paginate: {
                "first":      "처음",
                "last":       "마지막",
                "next":       "다음",
                "previous":   "이전"
            },
            aria: {
                sortAscending:  ": activate to sort column ascending",
                sortDescending: ": activate to sort column descending"
            }
        },
        "columnDefs": [
            // {
            //     "targets":[0,1,2,3],    // 0번부터 3번까지의 항목 선택
            //     "createdCell": function (td, cellData, rowData, row, col){
            //         $(td).addClass('');
            //         $(td).css("padding", "0");
            //         $(td).css("text-align","center");
            //
            //         if(col == 3){
            //             $(td).css("text-align","center");
            //         }
            //     }
            // },
            // {
            //     "targets": [2,3],		// 선택된 head 행의 sort 기능 사용여부
            //     "orderable": false
            // }
        ],
        "columns":[
            {
                data: "b_num",
                render: function (data){
                    return data;
                }
            },
            {
                data: "b_name",
                render: function (data){
                    return data;
                }
            },
            {
                data: "b_title",
                render: function (data){
                    return data;
                }
            },
            {
                data: "b_content",
                render: function (data){
                    return data;
                }
            },
            {
                data: "b_date",
                render: function (data){
                    return data;
                }
            },
        ]
    })
}


// 화면 접속 시 데이터 가져오기
$(document).ready(function (){
    $.ajax({
        url: "/board/searchList",
        type: "GET",
        success: function (data){
            if(data != null){
                board_data = data;
                boardInit(board_data);
            }
        }
    })
});

 

제일 많이 사용하는 기본 옵션들만 정리해두었다

language 옵션의 경우 매번 저렇게 길게 사용하기에는 가독성이 좋지 않으므로

공통으로 사용할 js 파일에 넣어두고 사용할 것을 추천한다.

columnDefs 옵션은 앞으로 그리려고 하는 <tbody> 의 데이터에 영향을 준다

target으로 선택된 행에 class 를 추가한다거나, 색을 넣는다거나, 해당 행을 display: none을 하여

DataTable에는 값이 있지만 사용자에게는 안 보이게 할 수도 있다.

 

 

DataTable의 css 가 깨진다면 아래 css를 선언했는지 확인한다.

현재 프로젝트는 head.html 내에 선언하였다.

<link th:href="@{/bootstrap/vendor/datatables/dataTables.bootstrap4.css}" rel="stylesheet" type="text/css" />

 

 

 

 

최종 화면

DataTable 설정한 옵션 기능

 

 

 

검색한 내용이 없을때

 

 

 

ajax로 데이터 가져오는 부분은 생략하였다

해당 부분은 Controller -> Service -> mapper 를 통해 List<vo> 로 가져오면 된다

댓글