728x90
HTTP request 헤더 조회
package hello.springmvc.basic.request;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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";
}
}
- HttpServletRequest / HttpServletResponse : 서블릿 기반의 reqeust / response 객체
- HttpMethod : HTTP 메서드를 조회한다.
- Locale : Locale(언어) 정보를 조회한다.
- @RequestHeader MultiValueMap<String, String> headerMap
- 모든 HTTP 헤더를 MultiValueMap 형식으로 조회한다.
- MultiValueMap은 Map과 유사한데, 하나의 키에 여러 값을 받을 수 있다.
- HTTP header, HTTP 쿼리 파라미터와 같이 하나의 키에 여러 값을 받을 때 사용한다.
- keyA=value1&keyA=value2
- @RequestHeader("host") String host
- 특정 HTTP 헤더를 조회한다.
- 속성
- 필수 값 여부 : required
- 기본 값 속성 : defaultValue
- @CookieValue : 특정 쿠키를 조회한다.
- 속성
- 쿠키 필수 값 여부 : required
- 쿠키의 기본값 지정 : defalutValue
- 속성
출력 결과
- 필요에 따라 헤더 정보를 가져온 뒤 파싱하거나, 특정 필드를 직접 조회해서 쓸 것
📌 MultiValueMap 사용 예제
MultiValueMap<String, String> map = new LinkedMultiValueMap();
map.add("keyA", "value1");
map.add("keyA", "value2");
//[value1,value2]
List<String> values = map.get("keyA");
- keyA=value1&keyA=value2
728x90
'[ Spring ] > SpringMVC 1편' 카테고리의 다른 글
[Spring] HTTP 응답을 보내는 방법 (정적 리소스 / 뷰 템플릿 / HTTP 메시지 ) (0) | 2022.02.26 |
---|---|
[Spring] HTTP 요청을 받는 방법 (요청 파라미터 / HTTP 요청 메시지) (0) | 2022.02.25 |
[Spring] 기본 매핑 / 요청 매핑 (0) | 2022.02.25 |
[Spring] 로깅 (Slf4j / Logback) (0) | 2022.02.24 |
[Spring] MVC 구조 (0) | 2022.02.22 |