개발/Spring

Spring MVC / Controller에서 요청을 매핑하는 방법

highright96 2021. 5. 27.

Controller에서 요청을 매핑하는 방법

클라이언트의 요청을 매핑해주는 어노테이션을 소개하려고 한다.

1. @RequestMapping

@RequestMapping(value = "/requestMapping", method = RequestMethod.GET)
public String requestMapping() {
  return "ok";
}

클라이언트의 url 요청을 매핑시켜주는 어노테이션이다.

value 값을 추가해 요청 url 경로를 지정해줄 수 있다. 또한 method 속성을 추가해 http method도 지정할 수 있다.

만약 method를 지정하지 않으면 http method와 무관하게 모든 url 요청에 호출된다.

 

2. @...Mapping

@GetMapping("/getMapping")
public String getMapping() {
  return "ok";
}

@RequestMapping에 method 속성을 추가하는 것은 너무 번거롭다.

따라서 스프링에서 축약 버전인 @GetMapping, @PostMapping, @PatchMapping, @PutMapping, @DeleteMapping를 제공한다.

미디어 타입 조건 매핑

1. consume

@PostMapping(value = "/postMapping-consume", consumes = MediaType.APPLICATION_JSON_VALUE)
public String mappingConsumes() {
  return "ok";
}

Controller에 매핑된 http 요청의 Content-Type을 지정한 타입으로 제한한다.

위의 예제는 Content-Type이 application/json형식이 아니면 415 상태 코드(Unsupported Media Type)를 반환한다.

 

2. produce

@PostMapping(value = "/postMapping-produce", consumes = MediaType.APPLICATION_JSON_VALUE)
public String mappingConsumes() {
  return "ok";
}

Controller에 매핑된 http 요청의 Accept를 지정한 타입으로 제한한다. Accept는 View에서 반환받을 수 있는 데이터 타입을 말한다.

위의 예제는 Accept이 application/json형식이 아니면 406 상태 코드(Not Acceptable)를 반환한다.

 

3. @PathVariable

최근 HTTP API는 아래와 같이 리소스 경로에 식별자를 넣는 경우가 많다.

/users/1
/users/1/item/2

위와 같은 식별자를 받기 위해서는 @PathVariable을 사용하면 된다.

참고로 @PathVariable의 이름과 파라미터의 이름이 같으면 생략할 수 있다.

// users/userA
@GetMapping("users/{userId}")
public String getPathVariableMapping(@PathVariable String id) {
  return "ok";
}

//생략 가능
@GetMapping("users/{userId}")
public String getPathVariableMapping(String userId) {
  return "ok";
}

 

4. 참고

댓글