일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- 강화학습
- 파이썬 오류
- 너비우선탐색
- 스택과 힙
- 파이썬
- post
- 오버라이딩
- 지도학습
- 이진탐색
- 코딩
- 코딩테스트
- 파이썬 알고리즘
- 머신러닝
- 캐싱
- 해시
- 비지도학습
- 백준
- 코테
- 프로그래머스
- 딕셔너리
- 알고리즘
- 깊이우선탐색
- 딥러닝
- Merge sort
- HTTP
- bineary search
- 멱등
- 자바
- rest api
- BOJ
- Today
- Total
chae._.chae
Spring boot 구조 및 폼 데이터 전송 본문
Model, View, Controller의 유기적 역할분담이 존재한다.
웨이터 : 주문받기, 주방장 : 음식만들기, 식재료담당자 : 재료준비하기 와 같은 원리이다.
1. controller : client에게 요청을 받는다.
2. view : 최종페이지를 만든다.
3. model : 최종페이지에 사용될 데이터를 view에게 전달한다.
MVC패턴은 디자인패턴 중 하나로, 좀 더 쉽고 편리하게 사용할 수 있도록 로직을 분리한 패턴이다.
사용자가 controller를 조작하면, controller는 model을 통해 데이터를 가져오고, 시각적인 화면을 담당하는 view를 제어해 사용자에게 전달하는 구조이다.
CREATE, READ, UPDATE, DELETE 기능이 가능한 게시판을 MVC패턴에 따라 개발해보자!
먼저, 사용자가 데이터를 입력하는 화면을 만들어준다. - (articles/new.mustache)
{{>layouts/header}} // 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">
</div>
<div class="mb-3">
<label class="form-label">내용</label>
<textarea class="form-control" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
{{>layouts/footer}} // layouts의 footer파일을 불러옴
다음으로는, 앞에서 만든 화면을 GetMapping을 이용하여 Controller와 매핑시켜준다. - (controller/ArticleController)
package com.example.firstproject.controller;
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 newArticleForm(){
return "articles/new"; // templates안에 articles/new.mustache 파일을 찾아 브라우저에 전송
}
// new.mustache에서 method="post"로 던졌기에 post로 받아준다.
// @PostMapping("어디로받을지")
@PostMapping("/articles/create")
public String createArticle(ArticleForm form){ // 폼데이터가 던져져서 온다.
System.out.println(form.toString()); // toString으로 찍어보기
return "";
}
}
@GetMapping("/articles/new")
- localhost:8080/articles/new에 접속하면, return "articles/new"에 따라 templates 안의 articles/new.mustache파일을 찾아 브라우저에 전송한다. 여기서 주의할 점은 , /news가 아닌, 파일 경로도 적어줘야한다.
@PostMapping("/articles/create")
- new.mustache에서 <form class="container" action="/articles/create" method="post">로 보낸 폼데이터를 PostMapping을 사용해서 받아준다.
- form태그에 데이터를 어디로(action), 어떻게(method) 보낼지에 대한 정보를 적어주어야 한다.
이때, 아래의 두 사진처럼 상단의 네비게이션바와 하단의 site-info부분이 동일한 것은 따로 빼서 작성해준다. (코드의 중복을 줄이고 깔끔하게 작성하기 위해)
사용자에게 보여지는 View를 겹치는 부분은
네비게이션바는 layouts/header.mustache에
하단의 site-info는 layouts/footer.mustache에 따로 작성해준다.
{{>layouts/header}} , {{>layouts/footer}}의 형태로 불러서 사용한다.
컨트롤러에서 폼데이터를 받을때, 객체로 담아서 받는데, 이를 DTO라 한다.
dto을 만들어준다. - (dto패키지/ArticleForm)
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 + '\'' +
'}';
}
}
하지만, 실행해보면, 값이 제대로 출력되지 않는다.
(title과 content에 모두 null값이 출력되어 내가 입력한 값이 들어가지 않는다.)
new.mustache에서 폼에서 변수명을 dto의 필드명과 동일한 이름으로 지정해준다.
-> title과 content가 dto와 연결되어 데이터가 전달된다.
해당 부분에 이름을 지정해서 넣어준다.
<input type="text" class="form-control" name="title">
<textarea class="form-control" rows="3" name="content"></textarea>
이름을 넣고 다시 실행해, 값을 넣어 submit버튼을 누르면, 아래처럼 내가 넣은 값이 출력된다!
'스프링' 카테고리의 다른 글
Github Action과 AWS CodeDeploy를 사용한 CI/CD 구축 방법 (0) | 2023.01.02 |
---|---|
Spring Boot로 AWS S3에 이미지 저장하기 (0) | 2022.07.25 |
JPA 활용 프로젝트 - (1) 도메인 분석 (0) | 2022.05.10 |
[Spring] 회원관리 예제 (0) | 2022.01.30 |
[Spring] 스프링 빈과 의존관계 (0) | 2022.01.21 |