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