본문 바로가기
Project/🥑JPA + SpringSecurity 게시판

[JPA + SpringSecurity 게시판] #6 글 리스트 만들기

by 로띠 2022. 4. 24.

 

 

지난 글에서 글쓰기를 완료하면 MySQL에는 Table과 Data가 알맞게 create되는데

아직 웹에서 클라이언트가 확인할 view가 없다 🥲

그래서 #5 에서는 간단하게 📋List 

mapping해줄 Controller, 비즈니스 처리 로직 Service, 클라이언트 view를 만들어 보자


 

 

 

👩🏻‍💻 코딩 시작

이미 글쓰기 로직을 만드는 과정에서 게시판관련 구조를 설계 했다

📋List 관련한 로직들을 기존 코드에 추가

 

 

 

1. Service

 

 

✅ BoardService 에 📋List를 구현하는 로직인 아래코드를 추가

getBoardList() 메소드로 게시글들을 모두 불러올 수 있다

 

[ BoardService ]

 

@Transactional
    public List<Board> getBoardList() {
        List<Board> boardList = boardRepository.findAll(Sort.by(Sort.Direction.DESC,"id","createdDate"));
        
        return boardList;
    }

 

✅ check ✅

@Transactional

모든 작업들이 성공적으로 완료되어야 작업 묶음의 결과를 적용

 

작업 도중 오류가 발생했을 때 이전 모든 작업들이 성공하였더라도 작업 전 시점으로 되돌린다

class, method() 에 적용이 가능하고, method() (소분류)가 우선 적용

  • JPA Service에는 필수

 

getBoardList()

  • List<Key,Value> 이며 <BoardDto> 를 재료로 한다
  • boardRepository 의 모든 것들을 조회하며 글번호(id) 기준으로 desc (최신 위)
    • id값이 안되면 createdDate로 설정

 

for (Board board : boardList) { }

  • boardList.size() 만큼 for문을 돌며 빌더패턴으로 객체 생성
  • Entity는 외부로 직접 전달하지 않고 DB와 소통 객체로만 쓰기 때문에 Dto로 변환
  • 빌더 패턴 사용 이유
    • 빌더패턴이 아닌 생성자, 수정자를 사용 중 BoardDto에 새로운 변수 nickName을 추가한다면,기존 코드들은
      nickName
      의 값이 없기때문에하지만 빌더패턴 사용 시
      <Optional>
      한 속성들을 유연하게 수행한다
    • 그래서 필요한 데이터만 설정이 가능하다
    • 기존 코드를 모두 수정하거나 생성자를 따로 추가해줘야한다

 


 

 

2. Controller

 

 BoardController 에 아래 코드를 추가 한다

현재 “/” 로 매핑되는데 “/list”로 하면 /list로 접속했을 때 비즈니스 로직을 호출한다

 

[ BoardController ]

@GetMapping("/")
    public String boardlist(Model model) {
        List<Board> boardList = boardService.getBoardList();
        model.addAttribute("boardList", boardList);
        return "board/list";
    }

 

✅ check ✅

getBoardList()

  • BoardService에 정의된 getBoardList() 호출해 List<Board> 에 담는다

 

model.addAttribute (”boardList”, boardList);

  • Model 객체를 이용해 (”Key”, “Value”) 로 저장하며
  • view에서 key로 value를 불러온다

 

 

 

🌸 번외 🌸

✅ 지난 글에서 List가 없기 때문에 글쓰기 완료 후 글쓰기 화면이 redirect되었는데

✅ List로 redirect하려면

write() 메소드

를 아래 코드로 수정

 

[ boardController ]

@PostMapping("/post")
    public String write(BoardDto boardDto) {
        boardService.savePost(boardDto);
        return "redirect:/";
    }

 


 

 

3. list.html

 

Thymeleaf 가 적용된 list.html

군데군데 Thymeleaf의 표현식이 사용된 게 보인다 🧐

 

[ list.html ]

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/layout}">

<div layout:fragment="content">
    <div class="container">
        <table class="table">
            <thead class="thead-light">
            <tr class="text-center">
                <th scope="col">no.</th>
                <th scope="col">제목</th>
                <th scope="col">작성자</th>
                <th scope="col">작성일</th>
            </tr>
            </thead>
            <tbody>
            <tr class="text-center" th:each="board : ${boardList}">
                <th scope="row">
                    <span th:text="${board.id}"></span>
                </th>
                <td>
                    <a th:href="@{'/post/' + ${board.id}}">
                        <span th:text="${board.title}"></span>
                    </a>
                </td>
                <td>
                    <span th:text="${board.author}"></span>
                </td>
                <td>
                    <span th:text="${#temporals.format(board.createdDate, 'yyyy-MM-dd HH:mm')}"></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>
</div>

 

✅ check ✅

 

<div layout:fragment="content">

  • 앞서 설정한 layout  layout:decorate="~{layouts/layout1}" 로 사용하고본문은 해당 태그부터 작성된다

 

<th:each="board : ${boardList}">

  • Controller에서 modelAttribute(”boardList”,”value”)로 보낸 값을Key인 boardList로 꺼내어 view에서는 board에 넣는다
  • boardList의 파라미터들을 꺼내 쓸때, id를 꺼낸다면
    ${board.id}
    사용

 

<a th:href="@{'/post/' + ${board.id}}">

  • @{ } 는 타임리프 주소 표현식으로
    • 상대적, 절대적, 파라미터를 포함한 주소 모두 가능
  • 위 코드에선 board.title 글 제목이나 번호를 누르면 해당 글의 board.id의 주소로 이동
  • 이후 글 상세보기 페이지에서 만들겠지만, 매핑된 컨트롤러 또한 파라미터를 갖는 주소
    @GetMapping("/post/{id}")
        public String detail(@PathVariable("id") Long id, {
    }

 

<th:text="${#temporals.format(board.createdDate, 'yyyy-MM-dd HH:mm')}">

  • ‘temporals ‘ 는 ‘시간의’ 라는 뜻으로 format을 정하여 날짜 출력이 가능
  • ‘연-월-일, 시-분’ 으로 출력

 

 

 

 

짜잔 🏖️

 

🤸🏻‍♀️

ㄲㅑ 최고다! 뒤집어진다~

 

 

다음편에선 글 상세보기 만들어 봐야짐

그럼 이만 👋