@GetMapping

Yuno·2024년 8월 18일
0

Spring Framework 에서 제공하는 어노테이션으로, HTTP GET 요청을 처리하는 메서드를 정의하는 데 사용됨. 이 어노테이션은 Spring MVC 컨트롤러에 사용되어 웹 어플리케이션의 특정URL 경로에 대한 GET 요청을 매핑함


👉 기본 사용법

@GetMapping 어노테이션은 @RequestMapping 어노테이션의 편의형으로, 기본적으로 method = RequestMethod.GET 을 설정해줌. 이를 통해 GET 요청을 처리하는 메서드를 간단히 정의할 수 있음.

import org.springframework.web.bind.annotation.GetMapping;
import org,springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class MyController {
	
    @GetMapping("/greeting")
    public String getGreeting() {
    	return "Hello, World!";
    }
}

@RestController 는 해당 클래스가 RESTful 웹 서비스의 컨트롤러임을 나타내며, @RequestMapping("/api") 는 클래스의 모든 메서드가 /api 경로를 기본으로 사용할 것임을 정의함. @GetMapping("/greeting")/api/greeting 경로로 들어오는 GET 요청을 getGreeting() 메서드가 처리하도록 매핑함


📌 매개 변수

@GetMapping 어노테이션은 다음과 같은 매개변수를 사용할 수 있음

  • value : 요청 경로를 지정. 여러 개의 경로를 배열 형태로 지정할 수도 있음
@GetMapping("/path1")
@GetMapping({"/path2", "/path3"})
  • params : 특정 요청 파라미터가 존재할 때만 매핑할 수 있음
@GetMapping(value = "/path", params = "id")
public String getById(@RequestParam String id) {
	return "ID: " + id;
}
  • headers : 특정 헤더가 존재할 때만 매핑할 수 있음
@GetMapping(value = "/path", headers = "Accept=application/json")
public String getJson() {
	return "JSON Response";
}
  • produces : 응답의 미디어 타입을 지정할 수 있음
@GetMapping(value = "/path", produces = "application/json")
public String getJson() {
	return "{\"message\":\"Hello, World!\"}";
}

📌 경로 변수와 요청 파라미터

@GetMapping 을 사용할 때 경로 변수와 요청 파라미터를 처리할 수 있음

  • 경로 변수 : URL 경로의 일부분을 변수로 사용하고 싶을 때 사용함
@GetMapping("/user/{id}")
public String getUserById(@PathVariable String id) {
	return "User ID: " + id;
}
  • 요청 파라미터 : 쿼리 문자열로 전달된 파라미터를 처리함
@GetMapping("/search")
public String search(@RequestParam String keyword) {
	return "Search keyword: " + keyword;
}

📌 예외 처리

@GetMapping 을 사용하는 메서드에서 예외가 발생하면, @ExceptionHandler 어노테이션을 사용하여 예외를 처리할 수 있음

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
	
    @GetMapping("/divide")
    public String divide(@RequestParam int numerator, @RequestParam int denominator) {
    	if (denominator == 0) {
        	throw new ArithmeticException("Cannot divide by zero");
        }
        return String.valueOf(numerator / denominator);
    }
    
    @ExceptionHandler(ArithmeticException.class)
    public String handleArithmeticException(ArithmeticException ex) {
    	return "Error: " + ex.getMessage();
    }
}
profile
Hello World

0개의 댓글