Reference <- https://ittrue.tistory.com/234
스프링 프레임워크의 모듈 중에는 웹 계층을 담당하는 몇 가지 모듈이 있다.
웹 계층에 서블릿(Servlet) API를 기반으로 클라이언트의 요청을 처리하는 모듈이 있는데 이를 스프링 웹 MVC(spring-web-mvc) 또는 스프링 MVC라고 한다.
Spring MVC는 클라이언트의 요청을 편리하게 해주는 기능을 제공한다.
서블릿은 클라이언트의 요청을 처리하도록 특정 규약에 맞춰 Java 코드로 작성하는 클래스 파일이다.
아파치 톰캣(Apache Tomcat)은 이러한 서블릿들이 웹 애플리케이션으로 실행할 수 있도록 해주는 서블릿 컨테이너(Servlet Container) 중 하나이다.
Spring MVC 내부에서는 서블릿을 기반으로 웹 애플리케이션을 동작하며, 스프링 부트는 기본적으로 아파치 톰캣이 내장되어 있다.
MVC 패턴은 애플리케이션을 개발할 때 사용하는 디자인 패턴이다.
애플리케이션의 개발 영역을 MVC(Model, View, Controller)로 구분하여 각 역할에 맞게 코드를 작성하는 개발 방식이다.
MVC 패턴을 도입하면서 UI 영역과 도메인(비즈니스 로직) 영역으로 구분되어 서로에게 영향을 주지 않으면서 개발과 유지보수를 가능하게 되었다.
서블릿이 호출되면 HttpServlet이 제공하는 service()가 호출된다.
스프링 MVC는 FramworkServlet.service()를 시작으로 여러 메서드가 호출되면서 DispacherServlet.doDispatch()가 최종적으로 호출된다.
핸들러 조회 : 핸들러 매핑을 통해 URL에 매핑된 핸들러(컨트롤러)를 조회한다.
핸들러 어댑터 조회 : 핸들러를 실행할 수 있는 핸들러 어댑터를 조회한다.
핸들러 어댑터 실행 : 핸들러 어댑터를 실행한다.
핸들러 실행 : 핸들러 어댑터가 실제 핸들러를 실행한다.
ModelAndView 반환 : 핸들러 어댑터는 핸들러가 반환하는 정보를 ModelAndView로 변환하여 반환한다.
viewResolver 호출 : 뷰 리졸버를 찾고 실행한다.
View 반환 : 뷰 리졸버는 뷰의 논리 이름을 물리 이름으로 바꾸고, 렌더링 역할을 담당하는 뷰 객체를 반환한다.
뷰 렌더링 : 뷰를 통해 뷰를 렌더링한다.
개별 헤더 정보 받기
@RestController
@RequestMapping(path = "/coffees")
public class CoffeeController {
@PostMapping
public ResponseEntity postCoffee(@RequestHeader("user-agent") String userAgent,
@RequestParam("name") String name,
@RequestParam("price") int price) {
System.out.println("user-agent: " + userAgent);
return new ResponseEntity<>(new Coffee(name, price), HttpStatus.CREATED);
}
}
전체 헤더 정보받기
@RestController
@RequestMapping(path = "/members")
public class MemberController {
@PostMapping
public ResponseEntity postMember(@RequestHeader Map<String, String> headers,
@RequestParam("email") String email,
@RequestParam("name") String name,
@RequestParam("phone") String phone) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
System.out.println("key: " + entry.getKey() +
", value: " + entry.getValue());
}
return new ResponseEntity<>(new Member(email, name, phone),
HttpStatus.CREATED);
}
}
HttpServletRequest 이용
HttpServletRequest 이용시, Request 헤더 정보에 다양한 방법으로 접근 가능
HttpServletRequest는 다양한 API를 지원함
단순히 특정 헤더 정보에 접근시에는 @RequestHeader를 사용하는 것을 추천
저수준(Low Level)의 서블릿 API를 사용할 수 있기때문에 복잡한 HTTP Request/Response를 처리하는데 사용
@RestController
@RequestMapping(path = "/v1/orders")
public class OrderController {
@PostMapping
public ResponseEntity postOrder(HttpServletRequest httpServletRequest,
@RequestParam("memberId") long memberId,
@RequestParam("coffeeId") long coffeeId) {
String userAgent = httpServletRequest.getHeader("user-agent");
System.out.println("user-agent: " + userAgent);
return new ResponseEntity<>(new Order(memberId, coffeeId),
HttpStatus.CREATED);
}
}
HttpEntity 이용
- Spring MVC에서는 HttpEntity 객체를 통해서도 헤더 정보를 읽을 수 있다.
- HttpEntity는 Request 헤더와 바디 정보를 래핑하고 있음
- 조금 더 쉽게 헤더와 바디에 접근할 수 있는 다양한 API를 지원
@RestController
@RequestMapping(path = "/v1/coffees")
public class CoffeeController{
@GetMapping
public ResponseEntity getCoffees(HttpEntity httpEntity) {
for(Map.Entry<String, List<String>> entry : httpEntity.getHeaders().entrySet()){
System.out.println("key: " + entry.getKey()
+ ", " + "value: " + entry.getValue());
}
// Host 정보도 가져올 수 있다.
System.out.println("host: " + httpEntity.getHeaders().getHost());
// host: localhost:8080
return null;
}
}
Reference
https://velog.io/@gwichanlee/Spring-HTTP-Header
https://ittrue.tistory.com/234