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라는 객체에 담겨서 들어오게 된다.