페이지 구성 (new.mustache)
<form class="container" action="/articles/create" method="post">
<div class="mb-3">
// 제목 Textbox
<label class="form-label">제목</label>
<input type="text" class="form-control" name="title">
</div>
<div class="mb-3">
// 내용 Textarea
<label class="form-label">내용</label>
<textarea class="form-control" rows="3" name="content"></textarea>
</div>
// Submit 버튼
<button type="submit" class="btn btn-primary">Submit</button>
</form>
- 위 form의 action은 submit 버튼을 누르면 /articles/create 를 post로 호출하도록 정의되었다.
- 제목 textbox의 내용은 title, 내용 textarea의 내용은 content로 전달된다.
Controller의 Post 동작 수행 (ArticleController)
Controller class는 @Controller annotation을 붙여준다.
Controller 내용 정의는 아래와 같다.
@Controller
public class ArticleController {
@PostMapping("/articles/create") // new.mustache > form의 action과 동일한 이름.
public String createArticle(ArticleForm form) { // ArticleForm 형태로 action 인자 값을 전달받는다.
System.out.println(form.toString());
return "";
}
}
DTO (Data Transfer Object)
Form에서 controller로 데이터를 전달할 때, DTO에 담아서 전달한다.
이 예제에서는 ArticleForm class를 DTO로 활용한다.
public class ArticleForm {
private String title;
private String content;
public ArticleForm(String title, String content) {
this.title = title;
this.content = content;
}
@Override // toString 재정의
public String toString() {
return "ArticleForm{" +
"title='" + title + '\'' +
", content='" + content + '\'' +
'}';
}
}
결과
제목과 내용을 입력 후 Submit 버튼을 클릭하면 ArticleForm{ title='제목', content='내용' } 형태로 debug 창에 출력된다.
'개발 > Spring Boot 학습' 카테고리의 다른 글
null value was assigned to a property [...] of primitive type (0) | 2023.05.02 |
---|---|
View Layout (0) | 2023.03.02 |
View Template, MVC (0) | 2023.02.23 |
개발 환경 및 Project 생성 (0) | 2023.02.23 |
Sprint Boot 학습 (0) | 2023.02.23 |