본문 바로가기
  • 시 쓰는 개발자
Spring

Controller vs RestController

by poetDeveloper 2024. 3. 9.

@Controller

@Controller는 보통 Spring MVC 패턴에서 view를 반환할 때 사용된다. home.html같이 view를 반환할 때는 Controller를 써도 되지만, 데이터를 반환한다면 Controller만으로는 부족하다. 그래서 필요한 것이 바로 @ResponseBody이다. 이것과 Controller를 함께 달아주면 데이터를 반환할 수 있다. 다만, 이 두개를 합쳐놓은 것이 RestController이다.

@RestController (= @ResponseBody + @Controller)

Controller와 ResponseBody를 합쳐놓은 것이 RestController이다. 그렇기때문에 @ResponseBody라는 어노테이션 없이도 @RestController만으로도 HTTP 바디부분에 자바 객체가 json으로 매핑되어 전달 된다. 프로젝트 경험상 대부분 RestAPI를 개발하며 RestController를 사용하기에 우리가 ResponseBody를 쓸 일은 많지 않아보인다.

@RestController와 함께 자주 쓰이는 것이 바로 ResponseEntity이다. ResponseEntity를 사용하면 객체를 반환하면서도 HTTP상태코드를 함께 전달할 수 있기 때문에 유용하다.

 

    @GetMapping("/checkID")
    public ResponseEntity<Object> checkIdDuplicate(@PathVariable String loginId) throws IOException {
        return ResponseEntity.ok(signupService.isIdDuplicate(loginId));
    }

 

'Spring' 카테고리의 다른 글

JPA N+1 문제  (0) 2024.05.05
annotation 정리  (0) 2024.03.11
RequestBody, ResponseBody  (0) 2024.03.08
Bean에 대하여  (0) 2024.03.08
Portable Service Abstraction  (2) 2024.03.04