Back-end/Spring

[Spring] HTTP 요청 - 기본, 헤더 조회

taeveloper 2022. 3. 21. 13:01

안녕하세요 이번 포스팅은 HTTP 요청을 받아서 컨트롤러에서 헤더를 포함한 여러 정보를 조회해보겠습니다.

 

애노테이션 기반의 스프링 컨트롤러는 다양한 파라미터를 지원합니다.

 

RequestHeaderController

 

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Slf4j
@RestController
public class RequestHeaderController {
     @RequestMapping("/headers")
     public String headers(HttpServletRequest request,
             HttpServletResponse response,
             HttpMethod httpMethod,
             Locale locale,
             @RequestHeader MultiValueMap<String, String>
            headerMap,
             @RequestHeader("host") String host,
             @CookieValue(value = "myCookie", required = false)
            String cookie
     ) {
             log.info("request={}", request);
             log.info("response={}", response);
             log.info("httpMethod={}", httpMethod);
             log.info("locale={}", locale);
             log.info("headerMap={}", headerMap);
             log.info("header host={}", host);
             log.info("myCookie={}", cookie);
             
             return "ok";
     }
}

HttpMethod : HTTP 메서드를 조회합니다. org.springframework.http.HttpMethod

Locale : Locale 정보를 조회합니다.

@RequestHeader MultiValueMap<String, String> headerMap : 모든 HTTP 헤더를 MultiValueMap 형식으로 조회합니다.

@RequestHeader("host") String host : 특정 HTTP 헤더를 조회합니다.

@CookieValue(value = "myCookie", required = false) String cookie : 특정 쿠키를 조회합니다.

필수 값 여부 : required

기본 값 : defaultValue

 

MultiValueMap

Map과 유사한데 하나의 키에 여러 값을 받을 수 있습니다.

HTTP header, HTTP 쿼리 파라미터와 같이 하나의 키에 여러 값을 받을 때 사용합니다.

 

다음 포스팅에서는 HTTP 요청 파라미터의 여러 종류에 대해서 알아보겠습니다!!