본문 바로가기

SpringMVC

[인프런 강의 복습]스프링 MVC 1편 - 요청 매핑

■ 요청 매핑

1) /hello-basic
- 기본 요청
- 둘다 허용 : /hello-basic, /hello-basic/
- HTTP 메서드 모두 허용 : GET, POST, PUT, DELETE, PATCH

2) /mapping-get-v1
- 특정 HTTP 메서드 요청만 허용
- POST 요청을 하면 스프링 MVC는 HTP 405 상태코드(Method Not Allowed)를 반환

3) /mapping-get-v2
- HTTP 메서드 매핑 축약
- 더 직관적
- @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping

4) /mapping/{userId]} - 단일, mapping/users/{userId}/orders/{orderId} - 다중
- 최근 HTTP API는 다음과 같이 리소스 경로에 식별자를 넣는 스타일을 선호-> /mapping/userA, /users/1
- @RequestMapping은 URL 경로를 템플릿화 할 수 있는데, @PathVariable을 사용하면 매칭 되는 부분을 편리하게 조회
- @PathVariable의 이름과 파라미터의 이름이 같을 경우 생략 가능

5) /mapping-param
- params = "mode"
- params != "mode"
- params = "mode=debug"
- params = "model!=debug"
- params = {"mode=debug", "data=good"}
- 특정 파라미터가 있거나 없는 조건을 추가, 잘 사용하지 X

6) /mapping-header
- header= "mode"
- header!= "mode"
- header = "mode=debug"
- header= "model!=debug"
- HTTP header 정보에 특정 파라미터의 값이 있거나 없는 조건을 추가하여 사용할 수 있다.

7) /mapping-consumes
- consumes="application/json"
- consumes="!application/json"
- consumes="application/*"
- MediaType.APPLICATION_JSON_VALUE
- 미디어 타입 조건 매핑 - HTTP 요청 Content-Type, consumes
- request body에 요청 데이터를 보낼 경우 consumes의 type을 application/json으로 설정한 경우, json 형식의 데이터를 body에 담아 보내야 한다.

8) /mapping-produce
- produces="text/html"
- produces="!text/html"
- produces="text/*"
- HTTP 요청의 Accep 헤더를 기반으로 미디어 타입으로 매핑
- 만약 맞지 않으면 HTTP 406 상태코드 (Not Acceptable)을 반환
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
public class MappingController {
    //private Logger log = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/hello-basic")
    public String helloBasic(){
        log.info("helloBasic");
        return "ok";
    }

    @RequestMapping(value = "/mapping-get-v1", method = RequestMethod.GET)
    public String mappingGetV1(){
        log.info("mapping-Get-V1");
        return "ok";
    }

    @GetMapping(value = "/mapping-get-v2")
    public String mappingGetV2(){
        log.info("mapping-Get-V2");
        return "ok";
    }
    
    @GetMapping(value = "/mapping/{userId}")
    public String mappingPath(@PathVariable("userId") String userId){
        log.info("mappingPath userId = {}", userId);
        return "ok";
    }
    
    @GetMapping("/mapping/users/{userId}/orders/{orderId}")
    public String mappingPath(@PathVariable String userId, @PathVariable Long orderId) {
        log.info("mappingPath userId={}, orderId={}", userId, orderId);
        return "ok";
    }

    //특정 파라미터의 정보(mode=debug)가 있어야지만 다음의 메서드가 호출
    @GetMapping(value = "/mapping-param", params = "mode=debug")
    public String mappingParam() {
        log.info("mappingParam");
        return "ok";
    }

    //헤더 정보에 설정된 값(mode=debug)이 설정되어 있어야 다음의 메서드가 호출
    @GetMapping(value = "/mapping-header", headers = "mode=debug")
    public String mappingHeader() {
        log.info("mappingHeader");
        return "ok";
    }

    @PostMapping(value = "/mapping-consume", consumes = "application/json")
    public String mappingConsumes() {
        log.info("mappingConsumes");
        return "ok";
    }

    @PostMapping(value = "/mapping-produce", produces = "text/html")
    public String mappingProduces() {
        log.info("mappingProduces");
        return "ok";
    }
}