[Spring] Spring 매핑 개념과 주요 애너테이션 활용법

URL과 컨트롤러 메서드를 연결하는 매핑 작업과 관련된 Spring 애너테이션(@RequestMapping, @GetMapping 등)의 활용법을 정리한 글입니다.


맵핑 (Mapping)

  • Mapping

    • 클라이언트로 부터 요청이 들어오는 URL과 컨트롤러 메서드를 연결하는 작업
    • Mapping 애너테이션을 사용해 클라이언트의 요청이 URL로 들어올 때 해당 URL에 맞는 컨트롤러가 있는지 확인하고 해당 컨트롤러를 매핑하여 요청을 처리
  • @RequestMapping

    • 클라이언트가 특정 URL로 요청을 보낼 때, 이 요청을 처리할 컨트롤러 메서드를 정의하는 것
    • Get, Post, Put, Delete, Patch등의 URL을 다 포함하고 있으며, 옵션을 통해 종류를 지정할 수 있음

      •   @Controller
          public class ProductController {
              @RequestMapping("/products", method = RequestMethod.GET)
              public String listProducts() {
                  return "product-list";
              }
        
              @RequestMapping("/products", method = RequestMethod.POST)
              public String addProducts() {
                  return "product-added";
              }
          }
        
  • HTTP 메서드에 특화된 매핑

    • @GetMapping
      • GET 요청만 받는 애노테이션
      • @RequestMapping(method = RequestMethod.GET)
    • @PostMapping
      • POST 요청만 받는 애노테이션
      • @RequestMapping(method = RequestMethod.POST)
    • @PutMapping
      • PUT 요청만 받는 애노테이션
      • @RequestMapping(method = RequestMethod.PUT)
    • @DeleteMapping
      • DELETE 요청만 받는 애노테이션
      • @RequestMapping(method = RequestMethod.DELETE)
    • @PatchtMapping
      • PATCT 요청만 받는 애노테이션
      • @RequestMapping(method = RequestMethod.PATCH)