2024. 3. 11. 17:49ㆍ스프링부트
package com.knu.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class MVCController {
@GetMapping("/")
public String hello(){
return "home";
}
@GetMapping("/get")
public String getStart(){
return "getInput";
}
@GetMapping("/post")
public String postStart(){
return "postInput";
}
@GetMapping("/post2")
public String APIpostStart(){
return "APIPostInput";
}
@GetMapping("/info")
public String getResult(
@RequestParam("name") String name,
@RequestParam("id") String id,
@RequestParam("department") String department,
Model model){
model.addAttribute("name",name);
model.addAttribute("id",id);
model.addAttribute("department",department);
return "getResult";
}
@PostMapping("/info")
public String postResult(
PostForm postForm,
Model model){
model.addAttribute("name",postForm.getName());
model.addAttribute("id",postForm.getId());
model.addAttribute("department",postForm.getDepartment());
return "postResult";
}
}
View에 thymeleaf 템플릿 엔진을 이용한다.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>start</title>
</head>
<body>
<div th:text = "'이름 : ' + ${name}"> </div>
<div th:text = "'학번 : ' + ${id}"> </div>
<div th:text = "'학과 : ' + ${department}"> </div>
</body>
</html>
위의 코드는 PostResult.html이다. (View)
Controller는 view에 model을 전달한다.
thymleaf는 model에 있는 내용들을 view에 전달하여 view를 완성하고 완성한 view를 반환한다.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>start</title>
</head>
<body>
<form action="/info" method="post">
이름 : <input type="text" name="name"><br>
학번 : <input type="text" name="id"><br>
학과 : <input type="text" name="department"><br>
<input type="submit">
</form>
</body>
</html>
위의 코드는 /info로 요청을 보내는 postinput.html이다
post요청을 보낼때 request body에 name=""&id=""&department="" 형식으로 서버에 post 요청한다.
그러면 스프링부트는 PostForm 형식으로 객체를 완성한다.
객체를 만들때 NoArgsConstructor로 객체를 생성하고 Setter를 통해 객체에 내용을 넣는다. (역 직렬화)
따라서 Setter와 NoArgsConstructor가 정의되어야한다.
만약 post요청을 json 형식으로 보내도 @RequestBody를 통해 이러한 객체 매핑을 가능하도록 만들 수 있다.
의문점 : Setter의 경우 객체가 변조될 가능성이 있는데 항상 Setter와 NoArgsConstructor를 써야하는 것인가??
1. DTO , VO, Entity를 따로 두어 해결할 수 있다.
DTO를 통해 객체 매핑을 시키고 VO나 Entity로 다른 생성 패턴과 도메인 로직을 구현하여 문제를 해결할 수 있다.
또한 DTO와 spring validation을 이용하여 DTO에 오는 값을 검증할 수 있다.
2. Jackson2HttpMessageConverter와 ObjectMapper에 대해 이해하고 설정을 변경한다.
HTTP 요청이 오면 Jackson2HttpMessageConverter가 ObjectMapper를 통해 요청을 역직렬화 한다. 스프링부트가 Jackson2HttpMessageConverter에 필요한 ObjectMapper에 대한 의존성을 주입해주는데 이러한 ObjectMapper를 설정하여 setter와 기본 생성자 없이 객체 매핑을 시킬 수 있다.
Object Mapper는 필드명, getter, setter, 기본생성자를 통해 property를 찾는다. 이러한 property와 기본 생성자를 위임 어노테이션에 명시해주면 그 정보를 이용해 직렬화 , 역직렬화를 한다.
또 위임 모듈이 존재하는데 이러한 위임 모듈은 위임 어노테이션에 설정할 정보를 자동으로 탐지해준다.
메세지 컨버터를 어떻게 설정할까?
setter와 기본 생성자가 있어야 직렬화, 역직렬화가 가능한데 우리가 쓰는 도메인은 변하면 안되는거 아닌가?
클라이언트가 보내는 요청을 어떻게 검증할까?
컨트롤러에서 어떻게 json을 받을까?
form 태그를 통한 요청은 어떤 형식으로 올까?
클라이언트에서 Json형식을 어떻게 서버에 보낼까?
어떤 원리로 직렬화 되는가?
builder 패턴을 어떻게 효율적으로 쓸 수 있을까?
form 데이터를 처리하는 여러 방식
URL를 파라미터로 어떻게 사용하는가? (@PathVariable)
'스프링부트' 카테고리의 다른 글
스프링 propertis (0) | 2024.03.15 |
---|---|
spring 동작 원리 (0) | 2024.03.11 |
스프링부트 시작하기 (0) | 2024.03.09 |
Spring Login API (0) | 2023.12.03 |
API 학습하기 (0) | 2023.12.03 |