컨트롤러에서 폼 데이터를 받기 위해서는 DTO(Data Transfer Object)에 담아 받는다.
웹페이지 만드는 순서에 대해서 얘기를 해보겠다.
1. 뷰 페이지를 만든다.
- Form 태그의 action 속성으로 데이터를 어디보낼지 결정하고
- method 설정으로 어떻게 보낼지 정의할 수 있다. (get or post)
2. 컨트롤러를 만든다.
- PostMapping 방식으로 URL 주소를 연결한다.
3. 전송받은 데이터를 담아둘 객체인 DTO를 생성한다.
4. 컨트롤러에서 폼 데이터를 전송받아서 해당 데이터를 DTO에 담는다.
1. 뷰페이지를 만든다.
{{>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>
</form>
{{>layouts/footer}}
2. 컨트롤러를 만든다.
package com.example.firstproject.controller;
import com.example.firstproject.dto.ArticleForm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class ArticleController {
@GetMapping("/articles/new")
public String newArticle() {
return "articles/new";
}
@PostMapping("/articles/create")
public String createArticle(ArticleForm form) {
System.out.println(form.toString());
return " ";
}
}
3. DTO 객체를 만든다.
package com.example.firstproject.dto;
public class ArticleForm {
private String title;
private String content;
public ArticleForm(String title, String content) {
this.title = title;
this.content = content;
}
@Override
public String toString() {
return "ArticleForm{" +
"title='" + title + '\'' +
", content='" + content + '\'' +
'}';
}
}
4. 실행해본다.
'코딩 공부 > Spirngboot' 카테고리의 다른 글
[Data조회과정과 생성과정] (0) | 2025.01.11 |
---|---|
[JPA] 개념 (0) | 2025.01.10 |
[MVC패턴] 기본 개념 (0) | 2025.01.08 |
[spring initializr] 시작 세팅 (0) | 2024.12.31 |
[Spring,SpringBoot] 스프링과 스프링부트 (0) | 2024.12.31 |