홍팍[스프링 부트 입문 07] 폼 데이터 주고 받기

Kevin·2022년 5월 10일
0

Mission 사용자로부터 폼 데이터를 받고, 이를 컨트롤러에서 확인하시오.

데이터가 담긴 객체를 **DTO**라 하고, 이를 Controller에서 받을 수 있다.

form 태그를 보낼 때는, How 와 Where의 정의가 필요하다.

<form class="container" action="/articles/create" method="post">

action = Where, method = How 에 해당된다고 할 수 있다.

폼 데이터를 받기 위해서는

@PostMapping("/articles/create")

How에 해당되는 방법의 Mapping을 사용해서 받을 수 있다.
객체로만 받을 수 있기 때문에, DTO를 만들어야 한다.

public class ArticleForm {
   private String title;
   private String content;

   public ArticleForm(String title, String content) {
       this.title = title;
       this.content = content;
   }
 }
 

DTO를 만들고, 생성자를 만들어준다.

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

앞서 생성한 DTO를 생성자로 받아올 수 있다.

<input type="text" class="form-control" name="title">
<textarea class="form-control" rows="3" name="content">

DTO에서 만든 변수인 "title" 과 "content"를 넣어주어야 값이 정상적으로 들어온다.

요약 정리
View 페이지를 만들고 form 태그에서 action과 method를 정의하고
Controller에서 PostMapping으로 받을 수 있으며, form데이터는 DTO라는 객체에 담겨서 들어오게 된다.

profile
성장해나가는 개발자입니다.

0개의 댓글