본문 바로가기
개발/Spring

@Controller vs @RestController의 차이

by lewns2 2021. 3. 15.

@Controller vs @RestController

Spring MVC 컨트롤러와 Restful 웹서비스 컨트롤러의 차이점은 "HTTP Response Body가 생성되는 방식"이다.

 

Spring 4.0 이상 버전 @Controller와 @ResponseBody 어노테이션을 추가하는 것 대신 @RestController을 제공한다. 

 

@RestController 어노테이션을 살펴보면, @Controller와 @ResponseBody 어노테이션이 있는 걸 확인할 수 있다.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 * @since 4.0.1
	 */
	@AliasFor(annotation = Controller.class)
	String value() default "";
}

 

 

@Controller는 일반적으로 View Page 이름을 리턴해주어 사용자에게 뷰페이지를 출력할 때 사용한다.

사용자의 요청 → Mapping → text/html 타입의 응답

 

@RestController는 View를 리턴하지 않고 컨트롤러에서 직접 데이터 리턴(HTTP Response Body 직접 작성)할 때 사용한다.

사용자의 요청 → Mapping → JSON/XML 형식의 HTTP 응답을 직접 작성

 

참고

doublesprogramming.tistory.com/105

wondongho.tistory.com/76

https://goddaehee.tistory.com/203 

 

 

728x90
반응형