IT/게시판 프로젝트

springboot 게시판 만들기 6 (게시글 리스트 조회 기능)

짐99 2023. 4. 14. 16:26
반응형

 

안녕하세요.

이전 글에서 게시글을 등록하였으니, 이번 글에서는 게시글의 목록을 보여줄 리스트 페이지를 구현해보겠습니당.

 

 

 

먼저 PostController에 리스트 메서드를 추가해줄게요.

@GetMapping("/post/list.do")
	public String openPostList(Model model) {
		List<PostResponse> posts = postService.findAllPost();
		model.addAttribute("poasts", posts);
		return "post/list";
	}

@GetMapping 어노테이션은 GET 방식의 HTTP 요청 메서드를 의미합니다. (GET은 데이터를 조회하거나 화면을 리턴하는 경우 사용!)

 

posts는 PostService의 findAllPost()의 실행 결과를 담은 게시글 리스트 객체입니다. 

Model 인터페이스의 addAttribute()를 이용해 "posts" 라는 이름으로 리스트 데이터를 화면(HTML)으로 전달합니다.

 

 

 

 

이제 return 한 post/list html을 작성해주겠습니다.

write.html 과 같은 경로에 list.html 파일을 추가한 후 코드를 작성해줄게요.

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="layout/basic">
    <th:block layout:fragment="title">
        <title>리스트 페이지</title>
    </th:block>

    <th:block layout:fragment="content">
        <div class="page_tits">
            <h3>게시판 관리</h3>
            <p class="path"><strong>현재 위치 :</strong> <span>게시판 관리</span> <span>리스트형</span> <span>리스트</span></p>
        </div>

        <div class="content">
            <section>
                <!--/* 검색 */-->
                <div class="search_box">
                    <form id="searchForm" onsubmit="return false;" autocomplete="off">
                        <div class="sch_group fl">
                            <select title="검색 유형 선택">
                                <option value="">전체 검색</option>
                                <option value="">제목</option>
                                <option value="">내용</option>
                            </select>
                            <input type="text" placeholder="키워드를 입력해 주세요." title="키워드 입력"/>
                            <button type="button" class="bt_search"><i class="fas fa-search"></i><span class="skip_info">검색</span></button>
                        </div>
                    </form>
                </div>
              
                <!--/* 리스트 */-->
                <table class="tb tb_col">
                    <colgroup>
                        <col style="width:50px;"/><col style="width:7.5%;"/><col style="width:auto;"/><col style="width:10%;"/><col style="width:15%;"/><col style="width:7.5%;"/>
                    </colgroup>
                    <thead>
                        <tr>
                            <th scope="col"><input type="checkbox"/></th>
                            <th scope="col">번호</th>
                            <th scope="col">제목</th>
                            <th scope="col">작성자</th>
                            <th scope="col">등록일</th>
                            <th scope="col">조회</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr th:if="${not #lists.isEmpty( posts )}" th:each="row, status : ${posts}">
                            <td><input type="checkbox"/></td>
                            <td class="tl"><a th:href="@{/post/view.do( id=${row.id} )}" th:text="${row.title}"></a></td>
                            <td th:text="${row.writer}"></td>
                            <td th:text="${#temporals.format( row.createdDate, 'yyyy-MM-dd HH:mm' )}"></td>
                            <td th:text="${row.viewCnt}"></td>
                        </tr>
    
                        <tr th:unless="${not #lists.isEmpty( posts )}">
                            <td colspan="5">
                                <div class="no_data_msg">검색된 결과가 없습니다.</div>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <!--/* 페이지네이션 */-->
                <div class="paging">
                    <a href="#" class="page_bt first">첫 페이지</a><a href="#" class="page_bt prev">이전 페이지 그룹</a>
                    <p><span class="on">1</span><a href="#">2</a><a href="#">3</a><a href="#">4</a><a href="#">5</a><a href="#">6</a><a href="#">7</a><a href="#">8</a><a href="#">9</a><a href="#">10</a></p>
                    <a href="#" class="page_bt next">다음 페이지 그룹</a><a href="#" class="page_bt last">마지막 페이지</a>
                </div>

                <!--/* 버튼 */-->
                <p class="btn_set tr">
                    <a th:href="@{/post/write.do}" class="btns btn_st3 btn_mid">글쓰기</a>
                </p>
            </section>
        </div> <!--/* .content */-->
    </th:block>
</html>

div.search_box는 게시글 목록에서 특정 게시글을 검색할 수 있는 영역입니다. (지금은 작동되지 않아요)

 

table.tb tb_col은 실제 컨텐츠가 들어가는 영역입니다. 

 

div.paging은 리스트에서 특정 페이지로 이동할 수 있는 페이지 번호 영역입니다. (지금은 작동되지 않아요)

 

<tbody> 태그 부분이 리스트 데이터가 출력되는 영역입니다.

th:if는 if 문과 거의 동일합니다. 그리고 th:unless는 else 문과 같다고 볼 수 있습니다. 하지만, ht:unless는 일반적인 else 문과는 달리 th:if와 동일한 조건을 지정해 주어야 합니다. 결과적으로 th:if 조건이 성립되면 게시글 리스트가 출력되고, th:unless 의 조건이 성립되면 "검색 조건이 없습니다."라는 메시지가 출력되게 됩니다.

th:each는 forEach와 유사한 기능입니다. row라는 이름으로 posts(리스트 객체)를 순환하며 출력하는 것입니다. 

<td class="tl"><a th:href="@{/post/view.do( id=${row.id} )}" th:text="${row.title}"></a></td>

이 부분은 제목을 클릭하면, 게시글 상세 페이지의 URL을 호출하는 것입니다. 타임리프는 URL 뒤에 괄호를 열어 파라미터로 전달합니다.

마지막으로 글쓰기 버튼을 누르면 저희가 이전에 만들었던 /post/write.do를 호출하여 신규 게시글 작성 페이지로 넘어가게됩니다.

 

 

 

이제 애플리케이션을 실행하여 결과를 보겠습니다. (localhost:8080/post/list.do)

저는 왜인지 검색된 결과가 없다고 뜨네요...

 

 

 

알고보니 위의 controller에서 오타가 있었네요

@GetMapping("/post/list.do")
	public String openPostList(Model model) {
		List<PostResponse> posts = postService.findAllPost();
		model.addAttribute("posts", posts);
		return "post/list";
	}

이렇게 고쳐주세요 ㅎㅎ..

 

 

그러면

리스트가 정상적으로 잘 뜨는 것을 확인할 수 있습니다!!

 

 

 

끗!

 

 

 

[참고 사이트]

출처 : https://congsong.tistory.com/17

반응형