Notice
Recent Posts
Recent Comments
Link
SeouliteLab
[Java/자바] Spring @RequestMapping: 요청 매핑과 핸들러 메서드 지정하기 본문
Spring 프레임워크에서 @RequestMapping 어노테이션은 요청과 컨트롤러 메서드를 매핑시킬 때 사용됩니다. 이 글에서는 @RequestMapping 어노테이션의 다양한 사용법과 예제 코드를 통해 자세히 알아보겠습니다.
1. 기본적인 @RequestMapping 사용법
가장 간단한 형태의 @RequestMapping 어노테이션은 다음과 같이 컨트롤러 메서드에 적용됩니다.
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
return "Hello, Spring!";
}
}
위의 예제에서는 /hello
경로로의 GET 요청에 대한 핸들러 메서드를 정의합니다.
2. 다양한 매핑 옵션
@RequestMapping 어노테이션은 여러 가지 매핑 옵션을 제공합니다.
예제 1: 경로 변수 사용
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public String getUser(@PathVariable("id") String userId) {
return "User ID: " + userId;
}
}
위의 예제에서는 /user/{id}
경로로의 GET 요청에 대한 핸들러 메서드를 정의하고, 경로 변수를 받아옵니다.
3. 예제 코드
다음은 @RequestMapping 어노테이션을 사용한 예제 코드입니다.
예제 1: 기본적인 @RequestMapping 사용법
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
return "Hello, Spring!";
}
}
예제 2: 경로 변수 사용
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public String getUser(@PathVariable("id") String userId) {
return "User ID: " + userId;
}
}
4. 결론
이상으로 Spring의 @RequestMapping 어노테이션에 대한 자세한 설명과 예제 코드를 살펴보았습니다. @RequestMapping 어노테이션을 사용하여 요청과 핸들러 메서드를 쉽게 매핑할 수 있습니다.
'프로그래밍' 카테고리의 다른 글
[Java/자바] Spring @GetMapping: HTTP GET 요청 처리하기 (0) | 2024.03.12 |
---|---|
[Java/자바] Spring @RequestParam: HTTP 요청 파라미터 처리하기 (0) | 2024.03.12 |
[Java/자바] Spring @ResponseStatus: HTTP 응답 상태 코드 지정하기 (0) | 2024.03.12 |
[Java/자바] Spring @ExceptionHandler: 예외 처리하기 (0) | 2024.03.12 |
[Java/자바] Spring @RequestHeader: HTTP 요청 헤더 처리 (0) | 2024.03.12 |