Controller와 RestController
서론
프로젝트 진행 중 프론트 개발을 JSP로 하면서 RestController를 사용했었었다.
그런데 이게 왠걸, 에러가 나는 것이 아닌가?
왜 에러가 나지… 하고 Controller로 바꿔보니 잘 작동하더라
그러다 문득 둘의 무슨 차이가 있는지 궁금해졌다.
그래서 오늘은 Controller와 RestController에 대해서 알아보려고 한다.
Controller와 RestController
한줄로 요약하면 HTTP Response가 생성되는 방식에 차이가 있다.
기존의 MVC @Controller는 View를 사용하지만,
@RestController는 반환 시 JSON/XML 타입의 HTTP 응답을 직접 리턴하게 된다.
이는 요즘 Front 개발이 주로 SPA 군단(React,Vue,Angular)이 지배하고 있어서
사실상 Spring MVC에서 V를 사용하는 일이 거의 없기 때문이 아닐까 추측해본다.
실행 흐름 순서
@Controller와 @RestController는 실행 순서가 다르다.
@Controller의 실행 순서
Client -> Request -> Dispatcher Servlet -> Handler Mapping -> Controller -> View -> Dispatcher Servlet -> Response -> Client
@ResponseBody의 실행 흐름
Client -> Request -> Dispatcher Servlet -> Handler Mapping -> Controller (ResponseBody)-> Response -> Client
@RestController의 실행 흐름
Client -> HTTP Request -> Dispatcher Servlet -> Handler Mapping -> RestController (자동 ResponseBody 추가)-> HTTP Response -> Client
즉 View의 유무에 따라 사용 용도가 다르다.
현재 나는 랜딩 프로젝트로 JSP를 사용하고 있는데, 프론트 페이지의 라우팅의 경우 Controller를 사용하는 것이 더 맞다고 할 수 있겠다.
Reference
https://lkg3796.tistory.com/58