220213_스프링입문_스프링 부트 시작하기_PUT API_패스트캠퍼스 챌린지 21일차
<2022년 02월 13일 _ 패스트캠퍼스 챌린지 21일차>
[스프링입문_스프링 부트 시작하기_PUT API]
1. 메소드의 특성
의미 | CRUD | 멱등성 | 안정성 | Path Variable | Query Parameter |
DataBody | |
GET | 리소스 취득 | R | O | O | O | O | X |
POST | 리소스 생성,추가 | C | X | X | O | △ | O |
PUT | 리소스 갱신, 생성 | C / U | O | X | O | △ | O |
DELETE | 리소스 삭제 | D | O | X | O | O | X |
HEAD | 헤더 데이터 취득 | - | O | O | - | - | - |
OPTIONS | 지원하는 메소드 취득 | - | O | - | - | - | - |
TRACE | 요청메시지 반환 | - | O | - | - | - | - |
CONNECT | 프록시 동작의 터널 접속으로 변경 | - | X | - | - | - | - |
2. 실습
(1) 프로젝트 생성 File > New > Project
: Artifact : put, Language: Java, Type: Gradle, Java: 11, Packaging: Jar
: Web > Spring Web 체크
(2) src > main > java > com.example.put 경로에 PutApiController 클래스 추가
(3) com.example.put 에 dto 패키지를 추가해주고, dto 패키지에 PostRequestDto, CarDto 클래스를 추가한다
package com.example.put.dto;
import java.util.List;
public class PostRequestDto {
private String name;
private int age;
private List<CarDto> carList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<CarDto> getCarList() {
return carList;
}
public void setCarList(List<CarDto> carList) {
this.carList = carList;
}
@Override
public String toString() {
return "PostRequestDto{" +
"name='" + name + '\'' +
", age=" + age +
", carList=" + carList +
'}';
}
}
package com.example.put.dto;
public class CarDto {
private String name;
private String carNumber;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCarNumber() {
return carNumber;
}
public void setCarNumber(String carNumber) {
this.carNumber = carNumber;
}
@Override
public String toString() {
return "CarDto{" +
"name='" + name + '\'' +
", carNumber='" + carNumber + '\'' +
'}';
}
}
package com.example.put;
import com.example.put.dto.PostRequestDto;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class PutApiController {
@PutMapping("/put")
public void put(@RequestBody PostRequestDto requestDto){
System.out.println(requestDto);
}
}
(4) Talend API에서 다음 json 데이터를 넘겨보자
{
"name" : "Makzuin",
"age" : 20,
"car_list" : [
{
"name" : "BMW",
"car_number" : "11가 1234"
},
{
"name" : "A4",
"car_number" : "11나 5678"
}
]
}
결과: PostRequestDto{name='Makzuin', age=20, carDtoList=null}
carDtoList 에 json 변수명이 매핑되어있지 않다!
(5) 이번엔 @JsonProperty 가 아니라 @JsonNaming으로 매핑해보자! 전체적으로 같은 규칙을 적용해 줄 수 있다
@JsonNaming(value = PropertyNamingStrategy.SnakeCaseStrategy.class)
PostRequestDto 클래스 위에 추가해준다.
결과:
PostRequestDto{name='Makzuin', age=20, carList=[CarDto{name='BMW', carNumber='null'}, CarDto{name='A4', carNumber='null'}]}
car_list 가 잘 들어간 것을 확인 할 수 있다. 하지만 carNumber는 아직이다?!!
(6) CarDto에는 @JsonProperty로 매핑해보자
: CarDto 클래스의 carNumber 변수에 다음과 같이 추가해준다
@JsonProperty("car_number")
private String carNumber;
결과:
PostRequestDto{name='Makzuin', age=20, carList=[CarDto{name='BMW', carNumber='11가 1234'}, CarDto{name='A4', carNumber='11나 5678'}]}
RestController의 경우엔 object를 return 시키면 스프링부트에서 자동으로 object mapper를 통해 json 형태로 바꿔준다
(7) PostRequestDto 에서 받은 requestDto를 그대로 return 해보자. 다음과 같이 소스 변경
package com.example.put;
import com.example.put.dto.PostRequestDto;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class PutApiController {
@PutMapping("/put")
public PostRequestDto put(@RequestBody PostRequestDto requestDto){
System.out.println(requestDto);
return requestDto;
}
}
결과: Response 에서도 json 형태로 잘 전달 된 것을 볼 수 있다.
@RestController | Rest API 설정 |
@RequestMapping | 리소스를 설정 (method로 구분가능) |
@PutMapping | Put Resource 설정 |
@RequestBody | Request Body 부분 Parsing |
@PathVariable | URL Path Variable Parsing |
(8) userId 를 받아보자~
package com.example.put;
import com.example.put.dto.PostRequestDto;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class PutApiController {
@PutMapping("/put/{userId}")
public PostRequestDto put(@RequestBody PostRequestDto requestDto, @PathVariable(name = "userId") Long id){
System.out.println(id);
return requestDto;
}
}
http://localhost:8080/api/put/100 로 Talend API에서 put요청을 보낸다~
콘솔 결과: 100
response 결과:
21일차 강의 완료~
패스트캠퍼스 [직장인 실무교육]
프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.
fastcampus.co.kr
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
'개발새발 > Spring' 카테고리의 다른 글
220215_스프링 입문_스프링 부트 시작하기_Response 내려주기 및 모범사례_패스트캠퍼스 챌린지 23일차 (0) | 2022.02.15 |
---|---|
220214_스프링입문_스프링 부트 시작하기_DELETE API_패스트캠퍼스 챌린지 22일차 (0) | 2022.02.14 |
220212_스프링입문_스프링 부트 시작하기_POST API_패스트캠퍼스 챌린지 20일차 (0) | 2022.02.13 |
220211_스프링입문_스프링 부트 시작하기_GET API(2)_패스트캠퍼스 챌린지 19일차 (0) | 2022.02.11 |
220210_스프링입문_스프링 부트 시작하기_GET API(1)_패스트캠퍼스 챌린지 18일차 (0) | 2022.02.10 |