SpringBoot 게시판 프로젝트

스프링부트(SpringBoot) 게시판 만들기 (6) - 게시글 상세 정보 조회/ 수정 기능 구현

얼뚱인데요 2024. 7. 4. 19:54
상세 글 조회 페이지 구현

 

PostController에 상세 페이지 조회 메서드 추가하기

// 게시글 상세 페이지
@GetMapping("/post/view.do")
public String openPostView(@RequestParam final Long id, Model model) {
    PostResponse post = postService.findPostById(id);
    model.addAttribute("post", post);
    return "post/view";
}

 

여기서 id는 PostMapper의 findById 쿼리의 WHERE 조건으로 사용되는 게시글 번호(PK)이다.

id를 파라미터값으로 전달받아 해당 id를 통해 postService의 findPostById메서드로 상세 정보(response 객체)를 조회하여  post라는 이름으로 화면에 전달한다.

이후 리턴문에 선언된 경로의 view.html 파일을 읽어 화면에 띄운다.

 

 

view.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>
                <table class="tb tb_row">
                    <colgroup>
                        <col style="width:10%;" /><col style="width:23%;" /><col style="width:10%;" /><col style="width:23%;" />
                    </colgroup>
                    <tbody>
                        <tr>
                            <th scope="row">글 유형</th>
                            <td th:text="${post.noticeYn == false ? '일반' : '공지'}"></td>
    
                            <th scope="row">등록일</th>
                            <td th:text="${#temporals.format( post.createdDate, 'yyyy-MM-dd HH:mm' )}"></td>
                        </tr>
                        <tr>
                            <th scope="row">제목</th>
                            <td>[[ ${post.title} ]]</td>
    
                            <th scope="row">조회</th>
                            <td colspan="3">[[ ${post.viewCnt} ]]</td>
                        </tr>
                        <tr>
                            <th scope="row">이름</th>
                            <td colspan="3">[[ ${post.writer} ]]</td>
                        </tr>
                        <tr>
                            <th scope="row">내용</th>
                            <td colspan="3">[[ ${post.content} ]]</td>
                        </tr>
                    </tbody>
                </table>
                <p class="btn_set">
                    <a th:href="@{/post/write.do( id=${post.id} )}" class="btns btn_bdr4 btn_mid">수정</a>
                    <button type="button" class="btns btn_bdr1 btn_mid">삭제</button>
                    <a th:href="@{/post/list.do}" class="btns btn_bdr3 btn_mid">뒤로</a>
                </p>
            </section>
        </div> <!--/* .content */-->
    </th:block>
</html>

 

 

글 상세 페이지

 

글 목록 페이지에서 등록되어있는 게시글의 제목을 클릭하면 해당 글의 상세 페이지로 이동한다.

뒤로 버튼을 누르면 게시글 목록 페이지(/post/list.do)로 이동한다.

삭제 기능은 아직 구현X

수정 버튼을 누르면 /post/write.do 가 요청이 되면서, 기존 글의 id값을 파라미터로 전달하여 나머지 상세 정보들을 불러와 기존 글이 그대로 화면에 노출이 되도록 할 것이다. 

글 상세 페이지 url

글 상세 정보 페이지를 들어가 url을 살펴보면 ' ? ' 뒤에 해당 게시글의 id 값이 적혀있다. 이를 쿼리스트링이라고 한다.

쿼리스트링이란?
파라미터의 정보가 " key=value " 형태의 문자열로 이루어진 것을 말한다. 쿼리스트링으로 연결된 URL은 GET 방식의 HTTP 요청 메소드임을 알 수 있다. 첫 번째 파라미터는 ' ? ' , 두 번째 파라미터부터는 ' & ' 으로 시작하여 구분한다.

 

 

수정 버튼 클릭 시 기존 글 화면에 띄우기

 

게시글 상세 페이지에서 수정 버튼을 누르면 파라미터로 id 값을 전달하여 아래 로직을 통해 상세정보를 화면에 출력하게 된다. 하지만 아직 write.html에는 게시글 상세정보를 화면에 랜더링 해주는 처리를 하지 않았기 때문에, 수정 버튼을 눌러도 기존 글 내용이 화면에 보이지 않는다.

 

디버깅 해보면 수정 버튼 클릭시 데이터는 담겨있는 걸 볼 수 있다.

 

 

렌더링 처리하는 자바스크립트 코드 작성하

- writle.html 에서 화면 렌더링 함수를 추가하고, onload() 함수가 렌더링 함수를 불러오도록 수정

window.onload = () => {
    renderPostInfo();
}

// 게시글 상세정보 렌더링
function renderPostInfo() {
    const post = [[ ${post} ]];

    if ( !post ) {
        initCreatedDate();
        return false;
    }

    const from = document.getElementById('saveForm');
    const fields = ['id', 'title', 'content', 'writer', 'noticeYn'];
    form.isNotice.checked = post.noticeYn;
    form.createdDate.value = dayjs(post.createdDate).format('YYYY-MM-DD HH:mm');

    fields.forEach(field => {
        form[field].value = post[field];
    })
}

 

새로운 게시글 작성 시에는 'post' 객체를 화면에 전달하지 않아 폼은 빈 상태로, 작성 날짜만 오늘 날짜로 설정된다.

기존 게시글 수정 시에는 전달하는 'post' 객체가 존재하여 이 값들을 폼 필드에 채워 미리 입력된 상태로 보여지는 것이다.  

더보기

사실 완전히 이해가 된 것 같지는 않아서 챗찌피티한테 무러봐땅

그렇다고 한다!

 

 

수정 버튼 클릭 시 기존 글 상세 정보가 화면에 랜더링 됨

 

 

게시글 수정 기능 실행 해보기

 

PostController에 기존 게시글 수정하는 메서드 추가

// 기존 게시글 수정
@PostMapping("/post/update.do")
public String updatePost(final PostRequest params) {
    postService.updatePost(params);
    return "redirect:/post/list.do";
}

 

 

게시글 수정 해보기

수정 사항 정상적으로 반영된 걸 확인함

 

DB 쿼리도 잘 작동 되어 반영됨.