SpringBoot

[3] IntelliJ 스프링부트 게시판_목록 출력하기

https.. 2024. 2. 13. 01:04

https://youtu.be/mJytzx8qIRI?feature=shared

 
작성한 글이 계속 데이터베이스에 업데이트되게 하려면 application.yml에서 ddl-auto: createupdate로 수정해준다.

 # spring data jpa 설정
  jpa:
    database-platform: org.hibernate.dialect.MySQLDialect
    open-in-view: false
    show-sql: true
    hibernate:
      ddl-auto: update

 

index.html에 목록 버튼 추가

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <button onclick="saveReq()">글작성</button>
    <a href="/board/save">글작성(링크)</a>
    <button onclick="listReq()">글목록</button>
</body>
<script>
  const saveReq = () => {
    location.href = "/board/save";
  }
  const listReq = () => {
    location.href = "/board/";
  }
</script>
</html>


BoardController에 목록 기능을 구현

    @GetMapping("/")
    public String findAll(Model model) {
        // DB에서 전체 게시글 데이터를 가져와서 list.html에 보여준다.
        List<BoardDTO> boardDTOList = boardService.findAll();
        model.addAttribute("boardList", boardDTOList);
        return "list";
    }


BoardService에 DTO

@Transactional
    public List<BoardDTO> findAll() {
        List<BoardEntity> boardEntityList = boardRepository.findAll();
        List<BoardDTO> boardDTOList = new ArrayList<>();
        for (BoardEntity boardEntity: boardEntityList) {
            boardDTOList.add(BoardDTO.toBoardDTO(boardEntity));
        }
        return boardDTOList;
    }


BoardDTO

public static BoardDTO toBoardDTO(BoardEntity boardEntity) {
        BoardDTO boardDTO = new BoardDTO();
        boardDTO.setId(boardEntity.getId());
        boardDTO.setBoardWriter(boardEntity.getBoardWriter());
        boardDTO.setBoardPass(boardEntity.getBoardPass());
        boardDTO.setBoardTitle(boardEntity.getBoardTitle());
        boardDTO.setBoardContents(boardEntity.getBoardContents());
        boardDTO.setBoardHits(boardEntity.getBoardHits());
        boardDTO.setBoardCreatedTime(boardEntity.getCreatedTime());
        boardDTO.setBoardUpdatedTime(boardEntity.getUpdatedTime());
        return boardDTO;
}


list.html 작성

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>list</title>
</head>
<body>
<table>
    <tr>
        <th>id</th>
        <th>title</th>
        <th>title(||쓰지 않은 경우)</th>
        <th>writer</th>
        <th>date</th>
        <th>hits</th>
    </tr>
    <tr th:each="board: ${boardList}">
        <td th:text="${board.id}"></td>
        <td><a th:href="@{|/board/${board.id}|}" th:text="${board.boardTitle}"></a></td>
        <td><a th:href="@{/board/${board.id}}" th:text="${board.boardTitle}"></a></td>
        <td th:text="${board.boardWriter}"></td>
        <td th:text="*{#temporals.format(board.boardCreatedTime, 'yyyy-MM-dd HH:mm:ss')}"></td>
        <td th:text="${board.boardHits}"></td>
    </tr>
</table>
</body>
</html>

 

글목록 버튼이 추가된 것을 확인할 수 있다.
 

글목록으로 들어오면 내가 작성한 글의 상세정보를 확인할 수 있다.