Notice
Recent Posts
Recent Comments
Link
SeouliteLab
[Java/자바] Spring @RequestParam: HTTP 요청 파라미터 처리하기 본문
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 요청 파라미터를 컨트롤러 메서드의 매개변수로 쉽게 처리할 수 있습니다.
'프로그래밍' 카테고리의 다른 글
[Java/자바] Spring @RestController: RESTful 웹 서비스를 위한 컨트롤러 > (0) | 2024.03.12 |
---|---|
[Java/자바] Spring @GetMapping: HTTP GET 요청 처리하기 (0) | 2024.03.12 |
[Java/자바] Spring @RequestMapping: 요청 매핑과 핸들러 메서드 지정하기 (0) | 2024.03.12 |
[Java/자바] Spring @ResponseStatus: HTTP 응답 상태 코드 지정하기 (0) | 2024.03.12 |
[Java/자바] Spring @ExceptionHandler: 예외 처리하기 (0) | 2024.03.12 |