SeouliteLab

[Java/자바] Spring @RequestBody: HTTP 요청의 본문을 메서드 파라미터로 받기 본문

프로그래밍

[Java/자바] Spring @RequestBody: HTTP 요청의 본문을 메서드 파라미터로 받기

Seoulite Lab 2024. 3. 12. 11:20

Spring 프레임워크에서 @RequestBody 어노테이션은 HTTP 요청의 본문을 메서드 파라미터로 전달받을 때 사용됩니다. 이 어노테이션을 사용하면 JSON, XML 또는 기타 형식의 요청 본문을 자바 객체로 변환할 수 있습니다. 이 글에서는 @RequestBody 어노테이션의 사용법과 예제 코드를 통해 자세히 알아보겠습니다.

1. 기본적인 @RequestBody 사용법

가장 간단한 형태의 @RequestBody 어노테이션은 다음과 같이 컨트롤러 메서드의 파라미터에 적용됩니다.

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @PostMapping("/message")
    public String handleMessage(@RequestBody String message) {
        return "Received message: " + message;
    }
}

위의 예제에서는 /message 경로로의 POST 요청의 본문을 String 형태로 받아와서 메서드의 파라미터로 사용합니다.

2. JSON 요청 본문을 객체로 변환하기

@RequestBody 어노테이션을 사용하면 JSON 요청 본문을 자바 객체로 변환할 수 있습니다.

예제 1: JSON 요청 본문을 객체로 변환하기

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @PostMapping("/user")
    public String createUser(@RequestBody User user) {
        // 사용자 생성 로직
        return "User created: " + user.getName();
    }
}

위의 예제에서는 /user 경로로의 POST 요청의 본문을 User 객체로 변환하여 사용합니다.

3. 예제 코드

다음은 @RequestBody 어노테이션을 사용한 예제 코드입니다.

예제 1: 기본적인 @RequestBody 사용법

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @PostMapping("/message")
    public String handleMessage(@RequestBody String message) {
        return "Received message: " + message;
    }
}

예제 2: JSON 요청 본문을 객체로 변환하기

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @PostMapping("/user

")
    public String createUser(@RequestBody User user) {
        // 사용자 생성 로직
        return "User created: " + user.getName();
    }
}

4. 결론

이상으로 Spring의 @RequestBody 어노테이션에 대한 자세한 설명과 예제 코드를 살펴보았습니다. @RequestBody 어노테이션을 사용하여 HTTP 요청의 본문을 메서드의 파라미터로 간편하게 받아올 수 있습니다.