ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 동적 콘텐츠 로딩
    웹 개발/JSP 2025. 3. 21. 16:55

    프로젝트 첫주차 프론트 쪽을 작업하며 탭이 바뀔때 컨텐츠 내용을 어떻게 동적으로 바꾸어주지 라는 고민을 하였다.

     

    여러가지 방법을 찾아보다 비동기적으로 내용을 바꾸어주는 방법으로 구현하였는데 전체 html을 처음부터 다 불러오지 않고 필요한 콘텐츠만 요청해서 가져오기 때문에 성능적으로 좋다.

     

    <h1 class="decorate-title-word">나의 꾸미기🎨</h1>
    	<div class="decorate-tab-container">
    		<button class="decorate-tab selected" onclick="showContent('전체')">전체</button>
    		<button class="decorate-tab" onclick="showContent('배경')">배경</button>
    		<button class="decorate-tab" onclick="showContent('스티커')">스티커</button>
    		<button class="decorate-tab" onclick="showContent('나무')">나무</button>
    	</div>
    	<div class="container" id="content-container">
    		<%@ include file="contents-sticker.jsp"%>
    	</div>

     

            function attachFolderItemClickEvent() {
                const folderItems = document.querySelectorAll(".folder-item");
                folderItems.forEach((item) => {
                    item.addEventListener("click", function () {
                        folderItems.forEach((el) => el.classList.remove("selected"));
                        this.classList.add("selected");
                    });
                });
            }
    
            function showContent(category) {
                document.querySelectorAll(".decorate-tab").forEach(tab => {
                    tab.classList.remove("selected");
                });
    
                document.querySelectorAll(".decorate-tab").forEach(tab => {
                    if (tab.textContent.trim() === category) {
                        tab.classList.add("selected");
                    }
                });
    
                let fileName = "";
                switch (category) {
                    case "전체":
                        fileName = "contents-all.jsp";
                        break;
                    case "배경":
                        fileName = "contents-background.jsp";
                        break;
                    case "스티커":
                        fileName = "contents-sticker.jsp";
                        break;
                    case "나무":
                        fileName = "contents-tree.jsp";
                        break;
                    default:
                        fileName = "contents-background.jsp";
                }
    
                fetch(fileName)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error("Network response was not ok");
                        }
                        return response.text();
                    })
                    .then(data => {
                        document.getElementById("content-container").innerHTML = data;
    
                        attachFolderItemClickEvent();
                    })
                    .catch(error => console.error("Error loading content:", error));
            }

     

    tab을 클릭하면 showContent함수가 실행된다.

    fileName을 담아서 fetch함수로 서버에 해당 jsp파일을 요청한다.

     

    document.getElementById("content-container").innerHTML = data;

    웹 페이지에서 id="content-container"인 요소를 찾아서 그 안에 data를 html로 삽입한다.

    화면의 일부가 바뀐다(새로고침 없이)

     

    이렇게 단순한 정적 include 방식 대신 fetch를 사용해 필요한 데이터만 동적으로 불러오는 방법은 프로젝트 성능을 개선할수 있다. 앞으로는 AJAX를 활용한 부분 렌더링과 동적 처리 방식에 익숙해져야겠다고 느꼈다.

     

    '웹 개발 > JSP' 카테고리의 다른 글

    Forward vs Redirect  (0) 2025.04.01
    JSP + MVC2 환경에서 AJAX 404 오류 해결  (1) 2025.04.01
    MVC2  (0) 2025.03.09

    댓글

Designed by Tistory.