@RequestMapping

Yuno·2024년 8월 18일
0

Spring MVC 에서 HTTP 요청을 특정 메서드에 매핑하는 데 사용하는 어노테이션.
HTTP 요청을 URL 패턴과 요청 메서드(GET, POST 등)를 기반으로 컨트롤러 메서드를 호출할 수 있음.


👉 기본 사용법

@RequestMapping 을 메서드에 사용하여 HTTP 요청을 처리할 수 있음

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 sayHello() {
    	return "Hello, World!";
    }
}

/hello 경로로 GET 요청이 오면 sayHello 메서드가 호출됨


👉 HTTP 메서드와 함께 사용

@RequestMapping 은 다양한 HTTP 메서드와 함께 사용할 수 있음. method 속성을 사용하여 지원하는 메서드를 지정할 수 있음

@RequestMapping(value = "/submit", method = RequestMethod.POST)
public String submitData(@RequestBody MyData data) {
	// POST 요청 처리
}

/submit 경로로 POST 요청이 들어오면 submitData 메서드가 호출됨


👉 경로 변수와 쿼리 매개변수

경로 변수 예시

@RequestMapping(value = "/greet/{name}", method = RequestMethod.GET)
public String greet(@PathVariable String name) {
	return "Hello, " + name + "!";
}

/greet/{name} 경로에서 {name} 부분이 변수로 취급되어 메서드 파라미터로 전달됨

쿼리 매개변수 예시

@RequestMapping(value = "/search", method = RequestMethod.GET)
public String search(@RequestParam String keyword) {
	return "Searching for: " + keyword;
}

/search?keyword=value 와 같은 쿼리 매개변수를 처리


👉 RequestMapping 의 다양한 속성

@RequestMapping 은 여러 속성을 지원함

  • value : URL 패턴
  • method : HTTP 메서드 (GET, POST 등)
  • params : 요청 매개변수
  • headers : 요청 헤더
@RequestMapping(
	value = "/items",
    method = RequestMethod.GET,
    params = "category=electronics",
    headers = "Accept=application/json"
)
public List<Item> getElectronicsItems() {
	// 전자 제품 아이템 반환
}

👉 RESTful API 와의 통합

RESTful API를 구축할 때는 @RequestMapping 보다 @GetMapping, @PostMapping, @PutMapping, @DeleteMapping 을 사용하는 것이 더 명확함

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ItemController {
	
    @GetMapping("/itmes")
    public List<Item> getItems(@RequestParam(required = false) String category) {
    	// 아이템 목록 반환
    }
    
    @PostMapping("/items")
    public Item addItem(@RequestBody Item item) {
    	// 아이템 추가
    }
    
    @PutMapping("/items/{id}")
    public Item updateItem(@PathVariable Long id, @RequestBody Item item) {
    	// 아이템 수정
    }
    
    @DeleteMapping("/items/{id}")
    public void deleteItem(@PathVariable Long id) {
    	// 아이템 삭제
	}
}
profile
Hello World

0개의 댓글