SeouliteLab

[Java/자바] Spring @RequestParam: HTTP 요청 파라미터 처리하기 본문

프로그래밍

[Java/자바] Spring @RequestParam: HTTP 요청 파라미터 처리하기

Seoulite Lab 2024. 3. 12. 11:09

Spring 프레임워크에서 @RequestParam 어노테이션은 HTTP 요청 파라미터를 컨트롤러 메서드의 매개변수로 바인딩할 때 사용됩니다. 이 글에서는 @RequestParam 어노테이션의 사용법과 예제 코드를 통해 자세히 알아보겠습니다.

1. 기본적인 @RequestParam 사용법

가장 간단한 형태의 @RequestParam 어노테이션은 다음과 같이 컨트롤러 메서드의 매개변수에 적용됩니다.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/hello")
    public String hello(@RequestParam("name") String name) {
        return "Hello, " + name + "!";
    }
}

위의 예제에서는 /hello 경로로의 GET 요청에 대한 핸들러 메서드를 정의하고, name 파라미터를 받아와서 사용합니다.

2. 다양한 매개변수 타입

@RequestParam 어노테이션은 다양한 매개변수 타입을 지원합니다.

예제 1: 기본 자료형 매개변수

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/sum")
    public int sum(@RequestParam("a") int a, @RequestParam("b") int b) {
        return a + b;
    }
}

위의 예제에서는 /sum 경로로의 GET 요청에 대한 핸들러 메서드를 정의하고, 두 개의 정수형 파라미터를 받아와서 더한 값을 반환합니다.

3. 예제 코드

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

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

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/hello")
    public String hello(@RequestParam("name") String name) {
        return "Hello, " + name + "!";
    }
}

예제 2: 다양한 매개변수 타입

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/sum")
    public int sum(@RequestParam("a") int a, @RequestParam("b") int b) {
        return a + b;
    }
}

4. 결론

이상으로 Spring의 @RequestParam 어노테이션에 대한 자세한 설명과 예제 코드를 살펴보았습니다. @RequestParam 어노테이션을 사용하여 HTTP 요청 파라미터를 컨트롤러 메서드의 매개변수로 쉽게 처리할 수 있습니다.