Mapping Requests - consumes, produces

EHOI·2025년 2월 11일

업무 중 코드를 보다가 컨트롤러에서 consumes 속성을 발견했는데 spring mvc 1편을 공부할 때도 나왔던 부분이라, spring 공식 문서를 통해 해당 내용을 한번 정리해보고자 한다.

Consumable Media Types

요청을 매핑할 때 Content-Type 을 기준으로 요청을 더욱 한정할 수 있다.

@PostMapping(path = "/pets", consumes = "application/json") // (1)
public void addPet(@RequestBody Pet pet) {
	// ...
}

(1) 이렇게 Mapping 어노테이션에 consumes 속성을 작성하면 Content-Type 을 Json으로 좁힐 수 있다.

consumes 속성은 반대로도 사용할 수 있다. !text/plain 이런 식으로 작성하면 text/plain 속성을 제외하고 나머지만 지원한다.

클래스 레벨에도 consumes 속성을 정의할 수 있다.

클래스 레벨에서 consumes 속성을 정의한 후, 메서드 레벨에서consumes 속성을 다시 정의하면, 메서드 레벨에서 사용한 게 클래스 레벨을 덮어쓴다.

MediaType 은 자주 쓰이는 타입을 상수로 제공한다.

ex)  APPLICATION_JSON_VALUE, APPLICATION_XML_VALUE

Producible Media Types

  1. produces 는 반환하는 데이터 타입을 정의한다.

    @GetMapping(path = "/pets/{petId}", produces = "application/json") // (1)
    @ResponseBody
    public Pet getPet(@PathVariable String petId) {
    	// ...
    }

    (1) 이 경우에는 반환 타입이 json으로 강제된다.

  2. Accept 요청 헤더에 대해서도 한정할 수 있다.

    서버로 요청하는 입장에서 Json 타입의 데이터를 원한다면 헤더에 아래와 같이 추가해서 요청한다

    Accept:application/json

클래스 레벨에도 produces 속성을 정의할 수 있다.

클래스 레벨에서 produces 속성을 정의한 후, 메서드 레벨에서produces 속성을 다시 정의하면, 메서드 레벨에서 사용한 게 클래스 레벨을 덮어쓴다.

References

https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-consumes

https://mungto.tistory.com/438

profile
#성장 #단단함 #평온함

0개의 댓글