활동/호기심

Spring Boot 게시글 업데이트 기능 구현 (Thymeleaf 활용 가이드)

ByeongJun 2023. 9. 22. 15:23
반응형

 

Spring Boot와 Thymeleaf 활용하여 게시글 수정 기능 구현 코드를 학습 목적으로

영상의 부분적인 내용을 다루고 있는 글이니 전체 내용이 필요한 분들은 

위의 링크를 통해 참고하시면 되겠습니다.

 

혹시라도 잘못된 내용이나 첨언해주실 내용이 있다면 댓글 부탁드립니다.

 

 

 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>게시물 수정폼</title>
</head>

<style>
  .layout {
    width: 500px;
    margin: 0 auto;
    margin-top: 200px;
  }

  .layout input {
    width: 100%;
    box-sizing: border-box;
  }

  .layout textarea {
    width: 100%;
    margin-top: 30px;
    min-height: 300px;
  }
</style>

<body>
<div class="layout">
  <form th:action="@{/board/update/{id}(id = ${board.id})}" method="post">
    <input name="title" type="text" th:value="${board.title}">
    <textarea name="content" th:text="${board.content}"></textarea>
    <button type="submit">수정</button>
  </form>
</div>
</body>
</html>

위의 코드는 Thymeleaf를 사용해 동적 웹 페이지를 생성하는 예시로써,  

서버에서 전달된 데이터를 화면에 표시하고 수정된 내용을 서버로 전송할 수 있다.

 

 

 

 <html lang="en" xmlns:th="http://www.thymeleaf.org">  문서를 시작할 때 

Thymeleaf 네임스페이스를 정의해 Thymeleaf의 표현식 및 속성을 사용한다. 

 

 

 

 th:action  속성을 사용해 <form> action 속성을 동적으로 설정하고, 

 th:value  및  th:text  속성을 사용해 입력 필드의 초기값을 설정한다. 

이러한 Thymeleaf 속성은 서버에 전달된 데이터를 HTML에 채워넣는 역할을 한다.

 

 

 

<style> 태그 안에서 layout을 건드려 위와 같이 만들었다.


 

 

 

 

 

// BoardService.java
public Board boardView(Integer id) {

    return boardRepository.findById(id).get();
}

 

  •  boardRepository.findById(id) 메서드 호출 시,
    해당 ID에 해당하는 게시글을 DB에서 찾아옴

  •  .get() 메서드 호출 시. 실제로 DB에서 가져온 게시글 정보를 얻음

  •  'boardRepository.findById(id)' 는 boardRepository에서
    id로 지정된 게시글을 찾아 반환하는 메서드 호출

 

 

 

 

 

// BoardController.java
@PostMapping("/board/update/{id}")
public String boardUpdate(@PathVariable("id") Integer id, Board board) {

     Board boardTemp = boardService.boardView(id);
     boardTemp.setTitle(board.getTitle());
     boardTemp.setContent(board.getContent());

     boardService.write(boardTemp);

     return "redirect:/board/list";
}

 

 @PostMapping("/board/update/{id}")  메서드는 수정된 정보를 받아서 

원본 게시글을 업데이트 하는 역할을 수행한다.

 

@PathVariable("id") 를 사용해 {id} 값인 게시글의 고유 ID를 가져오며

 Board boardTemp = boardService.boardView(id); 를 사용해

해당 ID에 해당하는 원본 게시글을 가져온다. 

 

Title과 Content를 업데이트 후 

 boardService.write(boardTemp); 를 통해 저장한다.

 

반응형