6. 게시판 내 페이지 이동하기

2024. 8. 5. 12:38코딩 자율학습 스프링 부트3 자바 백엔드 개발 입문 스터디

링크와 리다이렉트

  1. 링크
    • 미리 정해 놓은 요청을 간편히 전송하는 기능으로, 보통 페이지 이동을 위해 사용한다.
      • HTML의 <a> 태그 혹은 <form> 태그로 작성한다.
  2. 리다이렉트
    • 클라이언트의 요청을 받아 새로운 URL 주소로 재요청하라고 지시하는 것이다.

링크와 리다이렉트를 이용해 페이지 연결하기

새 글 작성 링크 만들기 - articles/index.mushtache

{{>layouts/header}}
<table class="table">
    <thead>
    <tr>
        <th scope="col">Id</th>
        <th scope="col">Title</th>
        <th scope="col">Content</th>
    </tr>
    </thead>
    <tbody>
    {{#articleList}}
        <tr>
            <td>{{id}}</td>
            <td>{{title}}</a></td>
            <td>{{content}}</td>
        </tr>
    {{/articleList}}
    </tbody>
</table>
<a href="/articles/new">New Article</a> 
{{>layouts/footer}}

  • <a> 태그 사용하여 링크를 추가한다.

입력 → 목록 페이지 이동 - articles/new.mustache

{{>layouts/header}}

<form class="container" action="/articles/create" method="post">
    <div class="mb-3">
        <label class="form-label">제목</label>
        <input type="text" class="form-control" name="title">
        </div>
    <div class="mb-3">
        <label class="form-label">내용</label>
        <textarea class="form-control" rows="3" name="content"></textarea>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
    <a href="/articles">Back</a>
</form>

{{>layouts/footer}}

입력 → 상세 페이지 이동 - controller/ArticleController

@PostMapping("/articles/create")
public String createArticle(ArticleForm form) {

    log.info("form 에서 전달된 데이터 : " + form.toString());

    // 1. DTO를 엔티티로 변환
    Article article = form.toEntity();
    log.info("DTO를 엔티티로 변환 : " + article.toString());

    // 2. 리포지토리로 엔티티를 DB에 저장
    Article saved = articleRepository.save(article);
    log.info("엔티티 DB 저장 : " + saved.toString());

    return "redirect:/articles/" + saved.getId();
}
  • redirect:/articles/{id} URL 로 이동할 수 있게 리다이렉트 지시를 작성해준다.
  • @Getter
    • saved.getId() 를 사용하기 위해 Article 엔티티에서 @Getter 를 사용하면 getter 메서드를 직접 만들지 않고 롬복을 이용해 사용할 수 있다.

상세 → 목록 페이지 이동 - article/show.mustache

{{>layouts/header}}
<table class="table">
    <thead>
    <tr>
        <th scope="col">Id</th>
        <th scope="col">Title</th>
        <th scope="col">Content</th>
    </tr>
    </thead>
    <tbody>
    {{#article}}
    <tr>
        <td>{{id}}</td>
        <td>{{title}}</td>
        <td>{{content}}</td>
    </tr>
    {{/article}}
    </tbody>
</table>
<a href="/articles">Go to Article List</a>
{{>layouts/footer}}

목록 → 상세 페이지 이동

<td><a href="/articles/{{id}}">{{title}}</a></td>
  • articles/index.mustache 파일에서 title에 링크를 걸어준다.