Back-end/Spring

[Spring] 요청 매핑

taeveloper 2022. 3. 21. 12:53

안녕하세요!! 이번 포스팅은 스프링에서 제공하는 기본적인 요청 매핑에 관해 알아보겠습니다.

 

MappingController

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

@RestController
public class MappingController {
 private Logger log = LoggerFactory.getLogger(getClass());
 
 /**
 * 기본 요청
 * 둘다 허용 /hello-basic, /hello-basic/
 * HTTP 메서드 모두 허용 GET, HEAD, POST, PUT, PATCH, DELETE
 */
 
     @RequestMapping("/hello-basic")
     public String helloBasic() {
         log.info("helloBasic");
         
         return "ok";
     }
}

 

HTTP 메서드

@RequestMapping에 method 속성으로 HTTP 메서드를 지정하지 않으면 HTTP 메서드와 무관하게 호출됩니다.

즉 GET, HEAD, POST, PUT, PATCH, DELETE를 모두 허용합니다.

 

HTTP 메서드 매핑

 

/**
 * method 특정 HTTP 메서드 요청만 허용
 * GET, HEAD, POST, PUT, PATCH, DELETE
 */
@RequestMapping(value = "/mapping-get-v1", method = RequestMethod.GET)
public String mappingGetV1() {
     log.info("mappingGetV1");
     return "ok";
}

만약 여기에 POST 요청을 하면 스프링 MVC는 HTTP 405 상태 코드(Method Not Allowed)를 반환합니다.

 

HTTP 메서드 매핑 축약

 

/**
 * 편리한 축약 애노테이션 (코드보기)
 * @GetMapping
 * @PostMapping
 * @PutMapping
 * @DeleteMapping
 * @PatchMapping
 */
@GetMapping(value = "/mapping-get-v2")
public String mappingGetV2() {
     log.info("mapping-get-v2");
     return "ok";
}

HTTP 메서드를 축약한 애노테이션을 사용하는 것이 더 직관적입니다. 코드를 보면 내부에서 @RequestMapping과 method를 지정해서 사용하는 것을 확인할 수 있습니다.

 

PathVariable(경로 변수) 사용

 

 * PathVariable 사용
 * 변수명이 같으면 생략 가능
 * @PathVariable("userId") String userId -> @PathVariable userId
 */
@GetMapping("/mapping/{userId}")
public String mappingPath(@PathVariable("userId") String data) {
     log.info("mappingPath userId={}", data);
     return "ok";
}

 

최근 HTTP API는 다음과 같이 리소스 경로에 식별자를 넣는 스타일을 선호합니다.

1. /mapping/userA

2. /users/1

 

@RequestMapping 은 URL 경로를 템플릿화 할 수 있는데, @PathVariable 을 사용하면 매칭 되는 부분을 편리하게 조회할 수 있습니다.

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

 

PathVariable 사용 - 다중

 

/**
 * 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";
}

 

특정 헤더 조건 매핑

 

/**
 * 특정 헤더로 추가 매핑
 * headers="mode",
 * headers="!mode"
 * headers="mode=debug"
 * headers="mode!=debug" (! = )
 */
@GetMapping(value = "/mapping-header", headers = "mode=debug")
public String mappingHeader() {
     log.info("mappingHeader");
     return "ok";
}

Postman으로 헤더에 값을 추가하고 테스트를 해보면 실행되는 것을 확인할 수 있습니다.

 

미디어 타입 조건 매핑 - HTTP 요청 Content-Type, consume

 

/**
 * Content-Type 헤더 기반 추가 매핑 Media Type
 * consumes="application/json"
 * consumes="!application/json"
 * consumes="application/*"
 * consumes="*\/*"
 * MediaType.APPLICATION_JSON_VALUE
 */
@PostMapping(value = "/mapping-consume", consumes = "application/json")
public String mappingConsumes() {
     log.info("mappingConsumes");
     return "ok";
}

위의 코드 또한 Postman으로 테스트해야 합니다.

HTTP 요청의 Content-Type 헤더를 기반으로 미디어 타입으로 매핑합니다.

만약 맞지 않으면 HTTP 415 상태 코드(Unsupported Media Type)를 반환합니다.

 

예시)

 

미디어 타입 조건 매핑 - HTTP 요청 Accept, produce

 

/**
 * Accept 헤더 기반 Media Type
 * produces = "text/html"
 * produces = "!text/html"
 * produces = "text/*"
 * produces = "*\/*"
 */
@PostMapping(value = "/mapping-produce", produces = "text/html")
public String mappingProduces() {
     log.info("mappingProduces");
     return "ok";
}

HTTP 요청의 Accept 헤더를 기반으로 미디어 타입으로 매핑합니다.

만약 맞지 않으면 HTTP 406 상태 코드(Not Acceptable)를 반환합니다.

 

예제)

 

 

요청 매핑 - API 예시

 

회원 관리를 HTTP API로 만든다 생각하고 매핑을 어떻게 하는지 알아봅시다.

 

 

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/mapping/users")
public class MappingClassController {
     /**
     * GET /mapping/users
     */
     @GetMapping
     public String users() {
     	return "get users";
     }
     
     /**
     * POST /mapping/users
     */
     @PostMapping
     public String addUser() {
     	return "post user";
     }
     
     /**
     * GET /mapping/users/{userId}
     */
     @GetMapping("/{userId}")
     public String findUser(@PathVariable String userId) {
     	return "get userId=" + userId;
     }
     
     /**
     * PATCH /mapping/users/{userId}
     */
     @PatchMapping("/{userId}")
     public String updateUser(@PathVariable String userId) {
     	return "update userId=" + userId;
     }
     
     /**
     * DELETE /mapping/users/{userId}
     */
     @DeleteMapping("/{userId}")
     public String deleteUser(@PathVariable String userId) {
     	return "delete userId=" + userId;
     }
}

 

 

다음 포스팅부터는 HTTP 요청에서 헤더 정보를 조회해보고 요청 파라미터에 대해서 알아보겠습니다!!