[Spring Boot/JPA] 게시판을 통해 MVC, CRUD 연습하기 3 - 상세보기
본문 바로가기

Web 개발/게시판 만들기

[Spring Boot/JPA] 게시판을 통해 MVC, CRUD 연습하기 3 - 상세보기

728x90
반응형

Spring Boot + H2 Database + JPA + Thymeleaf 을 활용해
간단한 게시판을 작성해보고자 합니다.
오늘 다룰 내용은 게시판 글 상세 내용 보여주기 기능입니다.

 

* 개발환경

Spring Boot : 2.4.3
Java 11
Thymeleaf 
Maven
War
Lombok

 

1. 글 제목 클릭 시, 상세페이지로 이동하도록

    List.html에서 글 제목에 Detail.html을 링크 걸기

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="contents">

	<a th:href="@{/write}">글쓰기</a>
    
    <table>
        <thead>
        <tr>
            <th class="one wide">번호</th>
            <th class="ten wide">글제목</th>
            <th class="two wide">작성자</th>
            <th class="three wide">작성일</th>
        </tr>
        </thead>

        <tbody>
        <!-- CONTENTS !-->
        <tr th:each="board, index : ${boardList}">
            <td>
                <span th:text="${index.index}"></span>
            </td>
            <td>
                <a th:href="@{'/list/' + ${board.id}}">
                    <span th:text="${board.title}"></span>
                </a>
            </td>
            <td>
                <span th:text="${board.writer}"></span>
            </td>
            <td>
                <span th:text="${#temporals.format(board.createdDate, 'yyyy-MM-dd HH:mm')}"></span>
            </td>
        </tr>
        </tbody>
    </table>
    
</div>

</body>
</html>

 

2. 상세페이지 만들기 Detail.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" th:href="@{/css/board.css}">
</head>
<body>

    <h2 th:text="${boardDto.title}"></h2>
    <p th:text="${boardDto.writer}"></p>
    <p th:inline="text">작성일: [[${#temporals.format(boardDto.createdDate, 'yyyy-MM-dd HH:mm')}]]</p>
    <p th:text="${boardDto.content}"></p>
    
</body>
</html>

 

4. Controller에 상세페이지 기능 추가

uri 가 /board/{id} 인 경우, Service에서 아이디에 해당하는 글을 찾아서 model을 통해 넘겨준다

package com.example.demo.controller;

import com.example.demo.domain.entity.Board;
import com.example.demo.dto.BoardDto;
import com.example.demo.service.BoardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Slf4j
@Controller
public class BoardController {

    private static final int page_size = 10;
    private BoardService boardService;

    public BoardController(BoardService boardService){
        this.boardService = boardService;
    }

    @GetMapping("/board")
    public String list(Model model){

        List<BoardDto> boardDtoList = boardService.getBoardList();
        model.addAttribute("boardList", boardList);

        return "list.html";
    }

    @GetMapping("/board/{no}")
    public String detail(@PathVariable("no") Long id, Model model){
        BoardDto boardDto = boardService.getPost(id);
        model.addAttribute("boardDto", boardDto);
        return "detail.html";
    }
    
}

 

5. 해당 Id 값을 갖는 게시글을 리턴하는 Service 구현

Repository를 통해 id값으로 객체를 찾아서 리턴한다.

package com.example.demo.service;

import com.example.demo.domain.entity.Board;
import com.example.demo.domain.repository.BoardRepository;
import com.example.demo.dto.BoardDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class BoardService {

    private BoardRepository boardRepository;

    public BoardService(BoardRepository boardRepository){
        this.boardRepository = boardRepository;
    }

    @Transactional
    public void savePost(BoardDto boardDto){
        boardRepository.save(boardDto.toEntity()).getId();
    }

    @Transactional
    public List<BoardDto> getBoardList(){
        List<Board> boards = boardRepository.findAll();
        List<BoardDto> boardDtoList = new ArrayList<>();

        for(Board board : boards){
            BoardDto dto = BoardDto.builder()
                    .id(board.getId())
                    .title(board.getTitle())
                    .content(board.getContent())
                    .writer(board.getWriter())
                    .createdDate(board.getCreatedDate())
                    .build();

            boardDtoList.add(dto);
        }
        return boardDtoList;
    }
    
    @Transactional
    public BoardDto getPost(Long id){
        Optional<Board> boardWrapper = boardRepository.findById(id);
        if(boardWrapper.isPresent())
        {
            Board board = boardWrapper.get();

            BoardDto boardDto = BoardDto.builder()
                    .id(board.getId())
                    .title(board.getTitle())
                    .content(board.getContent())
                    .writer(board.getWriter())
                    .createdDate(board.getCreatedDate())
                    .build();

            return boardDto;
        }

        return null;
    }
    
}

 

 

728x90
반응형