[Spring MVC] #4 기본 기능 (1) 요청 매핑

Jaeyoo (유재형)·2022년 2월 10일
0

SpringMVC

목록 보기
9/12
post-thumbnail

스프링MVC의 기본기능을 알아보자


요청 매핑


요청 매핑 : 요청이 왔을때 어떤 컨트롤러가 호출되어야하는지 매핑하는것

HTTP 메서드 매핑

@RequestMapping(value = "/mapping-get-v1", method=RequestMethod.GET) 

//메서드 매핑 축약
@GetMapping(value = "/mapping-get-v2")
  • 축약한 어노테이션을 사용하는것이 더 직관적

PathVariable (경로변수) 사용

@GetMapping("/mapping/{userId}")
  public String mappingPath(@PathVariable("userId") String data) {
      log.info("mappingPath userId={}", data);
      return "ok";
  }
  
//pathVariable 다중 사용
@GetMapping("/mapping/users/{userId}/orders/{orderId}")
  public String mappingPath(@PathVariable String userId, @PathVariable Long
  orderId) {
      log.info("mappingPath userId={}, orderId={}", userId, orderId);
      return "ok";
  }
  • URL 변수를 PathVariable을 통해 받을수있다.
  • @PathVariable의 이름과 파라미터의 이름이 같은면 생략 가능
    @PathVariable("userId") String userId== @PathVariable userId

특정 파라미터 조건 매핑

@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";
  }
 
  • HTTP 헤더의 조건을 본다.

미디어 타입 조건 매핑

Content-Type, consume
@PostMapping(value = "/mapping-consume", consumes = "application/json")
  public String mappingConsumes() {
      log.info("mappingConsumes");
      return "ok";
  }
  • HTTP 요청의 Content-Type 헤더를 기반으로 미디어 타입으로 매핑한다.
  • 맞지않다면 상태코드 415 반환
Accept, produce
@PostMapping(value = "/mapping-produce", produces = "text/html")
  public String mappingProduces() {
      log.info("mappingProduces");
      return "ok";
  }
  • HTTP 요청의 Accept 헤더를 기반으로 미디어 타입 매핑
  • 맞지않다면 상태코드 406 반환

참고 : @RestController

  • @Controller 는 반환 값이 String 이면 뷰 이름으로 인식된다. 그래서 뷰를 찾고 뷰가 랜더링 된다.
  • @RestController 는 반환 값으로 뷰를 찾는 것이 아니라, HTTP 메시지 바디에 바로 입력한다. 따라서 실행 결과로 ok 메세지를 받을 수 있다.

profile
기록과 반복

0개의 댓글