최대 1 분 소요

인프런 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술편을 학습하고 정리한 내용 입니다.

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

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

hello.springmvc.basic.request.RequestHeaderController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@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 headerMap
    • 모든 HTTP 헤더를 MultiValueMap 형식으로 조회한다.
  • @RequestHeader("host") String host
    • 특정 HTTP 헤더를 조회한다.
    • 속성
      • 필수 값 여부: required
      • 기본 값 속성: defaultValue
  • @CookieValue(value = "myCookie", required = false) String cookie
    • 특정 쿠키를 조회한다.
    • 속성
      • 필수 값 여부: required
      • 기본 값: defaultValue

참고
@Controller 의 사용 가능한 파라미터 목록은 다음 공식 메뉴얼에서 확인할 수 있다.
https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/arguments.html
@Controller 의 응답 가능한 목록도 다음과 같이 메뉴얼에서 확인 가능하다.
https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/return-types.html

태그:

카테고리:

업데이트:

댓글남기기