Explain the difference between spring @Controller and @RestController
annotation
Explain the difference between spring @Controller and @RestController
annotation
In the Spring framework, @Controller
and @RestController
are annotations used to define classes that can handle HTTP requests, but they serve different purposes and have distinct behaviors.
@Controller
AnnotationThe @Controller
annotation marks a class as a Spring MVC Controller, which is part of the Spring Web MVC framework. It is used to build traditional web applications that render views, typically returning HTML content. When a class is annotated with @Controller
, it becomes a candidate for auto-detection through classpath scanning and can be discovered by the Spring framework as a controller.
A @Controller
-annotated class handles incoming HTTP requests by using handler methods. These methods can return a view name, which is then resolved by a ViewResolver to render the response with a view technology like JSP or Thymeleaf. If you want a method in a @Controller
class to return a response body (like JSON or XML) instead of a view, you would use the @ResponseBody
annotation on the method level[1][2][3].
@RestController
AnnotationThe @RestController
annotation, introduced in Spring 4.0, is a specialized version of the @Controller
annotation that is designed for building RESTful web services. It is a convenience annotation that automatically includes the @Controller
and @ResponseBody
annotations. This means that all handler methods in a @RestController
-annotated class assume @ResponseBody
semantics by default, and the return value of each method is written directly to the HTTP response body, typically in a format like JSON or XML[1][2][3].
When using @RestController
, you do not need to annotate each handler method with @ResponseBody
, as you would with a traditional `@Control...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào