Spring/SpringMVC

HTTP 요청 - 기본, 헤더 조회

느리지만 꾸준하게 2022. 4. 29. 20:15

HTTP 헤더 정보를 조회하는 방법을 알아보자.

 

RequestHeaderController을 만들어 주고

package hello.springmvc.basic.request;


import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Local;
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

 

  • HttpMethod: HTTP 메서드를 조회한다. org.springframework.http.HttpMethod

 

  • Locale: Locale 정보를 조회한다.

 

 

 

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

 

 

  • @RequestHeader("host") String host
  • 특정 HTTP 헤더를 조회한다.
  • 속성
  • 필수 값 여부: required
  • 기본 값 속성: defaultValue

 

 

  • @CookieValue(value = "myCookie", required = false) String cookie
  • 특정 쿠키를 조회한다.
  • 속성
  • 필수 값 여부: required
  • 기본 값: defaultValue

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

postman으로 테스트 해주면 잘 나오는 것을 볼 수 있다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

<출처 김영한: 스프링 MVC 1편 - 벡앤드 웹 개발 핵심 기술>

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard

 

스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 - 인프런 | 강의

웹 애플리케이션을 개발할 때 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. 스프링 MVC의 핵심 원리와 구조를 이해하고, 더 깊이있는 백엔드 개발자로 성장할 수 있습니다., -

www.inflearn.com