Purple Bobblehead Bunny

Backend/SPRINGBOOT

[SpringBoot] 게시판 만들기 4. 게시글 상세 페이지

준영어린이 2022. 10. 31. 17:06

 

 

 

게시물 리스트를 만들었다. 여기서 게시글을 클릭을 하면 그 게시글에 대한 상세 페이지가 또 필요하다.

 

BoardController

BoardController에서  /board/view를 GetMapping 해 준 뒤,

Service로 가서 게시물 상세 리스트에 대한 코드를 구현한다.

 

여기서, 우리는 게시글을 불러올 때 어떤 게시글을 불러올지 지정을 해 줘야 하는데

매개변수로 Integer 값을 넣어줘야 한다.

Spring Data JPA 사용 시 Repository에서 return type을 Optional로 바로 받을 수 있도록 지원을 하고 있다.

get() 메서드를 이용해 반환된 객체를 꺼내 쓸 수 있게 된다.

 

다시 Controller로 가서 추가를 해 준다.

 

넘겨주기만 하고, 출력을 해 주는 부분은 따로 처리를 안해서 

마찬가지로 thymeleaf로 처리를 해 줘야 한다.

 

 

 

 

templates에서 boardview.html 을 작성 해 주 기전에

board/list로 가서 게시글 마다 링크를 띄워 줘야 하기 때문에 수정을 하러 가자.

 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>게시물 리스트</title>
</head>
<style>
    h2 {
      text-align: center;
    }
    .layout {
        width: 500px;
        margin: 0 auto;
        margin-top: 40px;
    }
</style>
<body>
<h2>게시물 리스트</h2>
<div class="layout">
    <table>
        <thead>
          <tr>
            <th>글번호</th>
            <th>제목</th>
          </tr>
        </thead>
        <tbody>
          <tr th:each="board : ${list}"> <!--each : 반복문 -->
            <td th:text="${board.id}"></td>
            <td>
                <a th:text="${board.title}" th:href="@{/board/view(id=${board.id})}"></a>
            </td>      
          </tr>
        </tbody>
    </table>
</div>
</body>
</html>

 

<td> 태그에 링크를 위한 <a> 태그를 추가 해 줬다.

th:href="@{/board/view(id=${board.id})

th:href는 링크를 위한 타임리프 문법이며, 

localhost:8080/board/view?id=board.id 이런 식으로 정리가 된다.

 

 

이제, 게시글 상세 페이지(boardview)를 만들러 가자 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>게시글 상세 리스트 </title>
</head>
<style>
  h2{
    text-align: center;
  }
</style>
<body>
    <h2>게시글 상세 리스트</h2><br><br><br>
    <h3 th:text="${board.title}"></h3>
    <p th:text="${board.content}"></p>
</body>
</html>

 

 

제목마다 링크가 생겼다! 아무거나 클릭해서 들어가게 되면

주소 창을 보면 id를 파라미터 값으로 받게 된다.