POST나 PUT 요청을 할 때는 주로 대용량의 폼 데이터나 복잡한 구조를 가진 JSON을 HTTP Body에 담아 서버로 전송합니다. 스프링 부트에서는 @RequestBody 어노테이션을 통해 들어오는 JSON 데이터를 우리가 정의한 자바 객체(DTO)로 자동으로 변환(역직렬화)해 줍니다.
💡 DTO (Data Transfer Object)란?
계층 간(클라이언트와 컨트롤러, 컨트롤러와 서비스 등) 데이터 교환을 위해 사용하는 순수한 데이터 객체입니다. Entity 객체를 직접 노출하지 않고 DTO를 사용함으로써 보안성과 유연성을 높일 수 있습니다.
실전 코딩: JSON 데이터를 DTO로 받기
UserCreateDto.java & UserController.java
// 1. 데이터를 받을 DTO 클래스 작성
package com.minstudio.demo.dto;
public class UserCreateDto {
private String name;
private int age;
// Getter와 Setter (스프링이 JSON을 파싱할 때 필요합니다)
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; }
}
// 2. 컨트롤러에서 처리
package com.minstudio.demo.controller;
import org.springframework.web.bind.annotation.*;
import com.minstudio.demo.dto.UserCreateDto;
@RestController
@RequestMapping("/api/users")
public class UserController {
// POST /api/users
@PostMapping
public String createUser(@RequestBody UserCreateDto dto) {
return "가입 완료! 이름: " + dto.getName() + ", 나이: " + dto.getAge();
}
}
POST localhost:8080/api/users (Body: {"name":"김철수", "age":25})