Spring

Spring @RequestParam 완벽 가이드

초코너무조코 2025. 2. 20. 11:35
728x90

Spring @RequestParam 완벽 가이드

Spring Boot를 활용하여 웹 애플리케이션을 개발할 때, 클라이언트로부터 데이터를 받는 방법 중 하나가 @RequestParam 어노테이션입니다. 이번 포스트에서는 @RequestParam의 사용법과 다양한 옵션을 살펴보겠습니다.

1. @RequestParam이란?

@RequestParam은 HTTP 요청의 쿼리 파라미터(query parameter)를 컨트롤러 메서드의 파라미터로 매핑할 때 사용됩니다. 주로 GET 요청에서 많이 활용되지만, POST, PUT 등에서도 사용할 수 있습니다.

2. 기본 사용법

기본적으로 @RequestParam을 사용하면, 클라이언트가 보낸 특정 파라미터 값을 컨트롤러의 메서드에서 사용할 수 있습니다.

@RestController
@RequestMapping("/api")
public class SampleController {
    @GetMapping("/greet")
    public String greet(@RequestParam String name) {
        return "Hello, " + name + "!";
    }
}

위와 같이 작성하면, http://localhost:8080/api/greet?name=John 요청을 보냈을 때 응답은 다음과 같습니다.

Hello, John!

3. 기본값 설정하기

쿼리 파라미터가 선택 사항이라면, defaultValue 속성을 사용하여 기본값을 지정할 수 있습니다.

@GetMapping("/greet")
public String greet(@RequestParam(defaultValue = "Guest") String name) {
    return "Hello, " + name + "!";
}

이제 name 파라미터 없이 http://localhost:8080/api/greet를 호출하면, 기본값 Guest가 적용됩니다.

Hello, Guest!

4. 필수 여부 설정하기

@RequestParam의 required 속성을 false로 설정하면, 해당 파라미터가 없어도 오류가 발생하지 않습니다.

@GetMapping("/greet")
public String greet(@RequestParam(required = false) String name) {
    return name != null ? "Hello, " + name + "!" : "Hello, Guest!";
}

5. 파라미터 이름과 매개변수 이름이 다를 때

@RequestParam을 사용할 때 쿼리 파라미터의 이름과 메서드 매개변수의 이름이 일치하지 않아도 됩니다. 이 경우 value 속성을 사용하여 매핑할 수 있습니다.

@GetMapping("/user")
public String getUser(@RequestParam("userName") String name) {
    return "User name: " + name;
}

요청 예제:

http://localhost:8080/api/user?userName=Alice

응답:

User name: Alice

6. 여러 개의 파라미터 받기

여러 개의 쿼리 파라미터를 받아 처리할 수도 있습니다.

@GetMapping("/user")
public String getUserInfo(@RequestParam String name, @RequestParam int age) {
    return "Name: " + name + ", Age: " + age;
}

요청 예시:

http://localhost:8080/api/user?name=Alice&age=25

응답:

Name: Alice, Age: 25

7. 리스트(List) 형태의 파라미터 받기

여러 개의 값을 리스트로 받을 수도 있습니다.

@GetMapping("/items")
public String getItems(@RequestParam List<String> items) {
    return "Selected items: " + String.join(", ", items);
}

요청 예시:

http://localhost:8080/api/items?items=apple&items=banana&items=cherry

응답:

Selected items: apple, banana, cherry

8. @RequestParam vs @PathVariable

@RequestParam은 URL의 쿼리 파라미터를 받아오지만, @PathVariable은 URL 경로에 포함된 값을 가져오는 차이가 있습니다.

@GetMapping("/user/{id}")
public String getUserById(@PathVariable String id) {
    return "User ID: " + id;
}

요청 예시:

http://localhost:8080/api/user/123

응답:

User ID: 123

9. 정리

  • @RequestParam은 주로 GET 요청의 쿼리 파라미터 값을 매핑하는 데 사용됩니다.
  • defaultValue를 사용하면 기본값을 설정할 수 있습니다.
  • required = false를 설정하면 선택적 파라미터로 만들 수 있습니다.
  • value 속성을 활용하면 파라미터 이름과 매개변수 이름을 다르게 설정할 수 있습니다.
  • 리스트 형태의 데이터도 받을 수 있습니다.
  • @PathVariable과는 용도가 다르므로 혼동하지 않도록 주의해야 합니다.

Spring Boot에서 클라이언트 요청을 효율적으로 처리하기 위해 @RequestParam을 적절히 활용해 보세요! 

728x90