JAVA, Spring
Spring Boot 링크, 리다이렉트
flykimjiwon
2023. 4. 4. 21:40
반응형
- 링크 : 요청을 위함
- 리다이렉트 : 응답을위함,클라이언트에게 다시 재요청을 한다.
기존 사이트의 문제점 새글 작성창도 없다. 이곳에 링크와 리다이렉트를 적용해야 한다.
1)글 전체 목록에서 새 글작성 페이지로 링크를 걸어준다.
왼쪽 아래에 New 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>
{{#articleList}}
<!-- articleList의 내용이 여러개인경우 안의 내용이 반복되서 출력된다.-->
<tr>
<td>{{id}}</td>
<td><a href="/articles/{{id}}">{{title}}</a></td>
<td>{{content}}</td>
</tr>
{{/articleList}}
</tbody>
</table>
<a href="/articles/new">New Article</a>
{{>layouts/footer}}
2) 목록 페이지로 돌아가기를 추가
Submit옆에 Back 링크를 추가했다.
{{>layouts/header}}
<form class="container" action="/articles/create" method="post">
<!-- action 어디로, method 어떻게-->
<div class="mb-3">
<label class="form-label">subject</label>
<input type="text" class="form-control" name="title">
</div>
<div class="mb-3">
<label class="form-label">content</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}}
3)새 글을 저장하면 각 글의 상세페이지로 가게 만들기
마지막 return 부분을 아래와 같이 바꿔주었다.
return "redirect:/articles/" + saved.getId();
show.mustache
.........
@PostMapping("/articles/create")
public String createArticle(ArticleForm form){
// dto에 있는거냐 물음표 나오면 알트 엔터 무슨 문제였을까?
// System.out.println(form.toString()); -> 로깅기능으로 대체하기
log.info(form.toString());
// 1.Dto를 변환 Entity로!
Article article = form.toEntity();
// System.out.println(article.toString());
log.info(article.toString());
// 2. Repository에게 Entity를 DB에 저장하게 한다.
Article saved = articleRepository.save(article);
// System.out.println(saved.toString());
log.info(saved.toString());
//Crud 리포지토리 기능 가져와서 사용할 수 있다.
// return "redirect:/articles";
return "redirect:/articles/" + saved.getId();
// 이곳에 리다레익트 적용시켜주기
}
.........
반응형