카테고리 없음
[SpringBoot] 별도의 페이지(엔드 포인트) 없이 모달로 "로그인", "회원가입" 구현하기
MoveForward
2025. 6. 8. 21:38
기존에 구현하던 페이지 방식은
- "/members/login" - 로그인 페이지
- "/members/join" - 회원가입 페이지
이와 같이 한개의 엔드 포인트를 가진 페이지 구성 방식이었다.
그러나, 이번 방식은 별도의 엔드 포인트를 가지는 것이 아닌 메인 페이지("/" - index.html)에서 버튼을 통해 로그인, 회원가입 모달을 생성하는 방식으로 구현하는 것이다.
메인 페이지("/" - index.html) 좌측 상단에 위치한 "Login" , "Sign Up" 버튼을 통해 모달을 생성한다.
왼쪽은 로그인 모달이고, 오른쪽은 회원가입 모달이다.
[구현 방식]
이와 같은 프로젝트 트리를 가진다.
login.html - 로그인 모달 구현
signup.html - 회원가입 모달 구현
이때, 2개의 모달은 "static" 아래 위치해있어야 한다.
정적 리소스 취급을 하여야 도구로서 사용할 수 있다.
만약, "templates" 아래 있으면 fetch()는 JSP/Thymeleaf 렌더링이 안되므로 HTML로 못 읽는다.
<!-- index.html -->
<!-- 로그인 / 회원가입 버튼 -->
<a href="#" class="btn btn-outline-primary" id="openLoginBtn">Login</a>
<a href="#" class="btn btn-primary" id="openSignupBtn">Sign Up</a>
//index.js
const loginBtn = document.getElementById('openLoginBtn');
const signupBtn = document.getElementById('openSignupBtn');
const modalContainer = document.getElementById('modal-container');
// 모달 닫기
function closeModal() {
modalContainer.style.display = 'none';
modalContainer.innerHTML = '';
}
// 모달 열기 (파일 이름을 받아서 fetch + Bootstrap 모달 실행)
function loadModalContent(file, modalId) {
fetch(file)
.then(response => response.text())
.then(html => {
console.log('받은 HTML:', html); // 이거 추가
modalContainer.innerHTML = html;
modalContainer.style.display = 'block';
// 모달 객체를 찾아서 띄우기 (Bootstrap Modal 가정)
const modalElement = document.getElementById(modalId);
const bootstrapModal = new bootstrap.Modal(modalElement);
bootstrapModal.show();
// 모달이 닫히면 modalContainer 초기화
modalElement.addEventListener('hidden.bs.modal', () => {
closeModal();
});
})
.catch(err => {
console.error('모달 로딩 실패:', err);
});
}
// 이벤트 핸들러 연결
loginBtn.onclick = () => loadModalContent('login.html', 'loginModal');
signupBtn.onclick = () => loadModalContent('signup.html', 'signupModal');
[어려웠던 점]
모달 HTML 파일의 위치를 templates 아래 두어 에러가 발생했는데, 원인을 찾는데 가장 많은 시간을 사용하였다.