본문 바로가기
Spring/spring boot

spring boot를 사용한 게시판 만들기(3): 게시판 목록 출력

by 성장호소 2024. 4. 6.

게시판 화면을 띄우기 위해 html파일을 가져와 보자.

 

부트스트랩을 사용하기 위해 build.gradle파일에 dependencies 설정을 추가해 줘야 한다.

 

resources/templates/board 폴더를 만들어 list.html 파일을 넣어두자.

<list.html>

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>게시판 - 목록</title>
    <link rel="stylesheet" href="/webjars/bootstrap/4.5.0/css/bootstrap.min.css" />
</head>
<body>
<header th:insert=" common/header.html"></header>
<div class="container">
    <table class="table">
        <thead class="thead-light">
        <tr class="text-center">
            <th scope="col">#</th>
            <th scope="col">제목</th>
            <th scope="col">작성자</th>
            <th scope="col">내용</th>
        </tr>
        </thead>
        <tbody>
        <tr class="text-center" th:each="post : ${postList}">
            <th scope="row">
                <span th:text="${post.id}"></span>
            </th>
            <td>
                <a th:href="@{'/post/' + ${post.id}}">
                    <span th:text="${post.title}"></span>
                </a>
            </td>
            <td>
                <span th:text="${post.author}"></span>
            </td>
            <td>
                <span th:text="${post.content}"></span>
            </td>
        </tr>
        </tbody>
    </table>
    <div class="row">
        <div class="col-auto mr-auto"></div>
        <div class="col-auto">
            <a class="btn btn-primary" th:href="@{/post}" role="button">글쓰기</a>
        </div>
    </div>
</div>
<script src="/webjars/jquery/3.5.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</body>
</html>

 

모든 화면에서 공통으로 사용하는 헤더 파일인 header.html 은 resources/templates/common 폴더에 저장해줬다.

<header.html>

<div class="navbar navbar-dark bg-dark shadow-sm mb-3">
    <div class="container d-flex justify-content-between">
        <a href="/" class="navbar-brand d-flex align-items-center">
            <strong>게시판</strong>
        </a>
    </div>
</div>

 

이제 사용자가 localhost:8080 으로 들어가면 게시판 목록이 화면에 나오도록 BoardController 메서드를 만들자.

MVC

localhost:8080 로 들어가면 @GetMapping 을 통해 위 메서드를 실행하게 된다. 

컨트롤러가 "board/list" 문자열과 서비스를 통해 DB에 저장된 게시글 목록을 가져온 postList를 모델에 담아 viewResolver에게 준다.

 

 

그러면 viewResolver가 templates 하위 폴더에서  문자열과 같은 board/list.html 파일로 찾아 들어가 모델에 담아져 온 postList를 Thymeleaf 템플릿 엔진으로 처리한 후 변환된 html 파일을 웹 브라우저로 보여준다.

 

 

 

그리고 스프링 메인 클래스를 실행시키면 다음과 같은 화면이 띄워진다.

아직 DB에 저장된 것이 없어서 아무 것도 없는데 다음 글에서 게시글을 추가하고 수정, 삭제를 해보자.