코딩 기록들
스프링 입문 4.3 PUT API 본문
리소스의 갱신및 생성 : 리소스가 없으면 생성, 있으면 기존것을 업데이트
멱등한 이유 : 처음한번은 데이터 생성, 그다음에는 데이터가 없데이트됨 = 데이터는 '하나'
put 어노테이션
@RestController - RestAPI 설정
@RequestMapping - 리소스를 설정(메소드로 구분가능) : resource 의 api 주소 설정용
@PutMapping- Put Resource(path reosource) 설정
@RequestBody - Request Body 부분 Parsing
@PathVariable - URL path Variable Parsing
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;
// 어떻게 리스펀스는 내려줄것인가? - 1) RestController : object자체를 리턴시키면
}
}
package com.example.put.dto;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.List;
@JsonNaming(value = PropertyNamingStrategy.SnakeCaseStrategy.class) //해당클래스는 objext mapper라는 모듈이 동작할때,
// snake case로 인식한다 -> 해당클래스에 일관적으로 모든 JSON룰을 적용시킬수있음
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;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CarDto {
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;
}
private String name;
@JsonProperty("car_number")
private String carNumber; // 카멜케이스이므로 JSONProperty 어노테이션 사용
@Override
public String toString() {
return "CarDto{" +
"name='" + name + '\'' +
", carNumber='" + carNumber + '\'' +
'}';
}
}
JSON
{
"name" : "steve",
"age" : 20,
"car_List" : [
{
"name" : "BMW",
"car_number" : "가1234"
},
{
"name" : "A4",
"car_number" : "나3456"
}
]
}
'스프링 입문' 카테고리의 다른 글
스프링 입문 5.1 스프링의 핵심 (1) | 2024.01.05 |
---|---|
스프링 입문 4.4 DELETE API (0) | 2024.01.05 |
스프링 입문 4.3 POST API (3) | 2024.01.03 |
스프링 입문 4.2 GET API (3) | 2024.01.03 |
스프링 입문 4.1 Hello World API 만들기 (Talend API Tester 사용) (0) | 2024.01.03 |