Spring MVC Tutorial
Core Spring MVC
Spring MVC - Annotation
Spring MVC - Form Handling
Spring MVC with JSTL
Spring MVC with REST API
Spring MVC with Database
In Spring, both @Controller
and @RestController
annotations are used to define a controller in a Spring MVC application. However, they serve slightly different purposes, particularly concerning the type of response they produce.
Here's a breakdown of their differences:
@Controller:
@Controller
are expected to return a view name (like the name of a JSP, Thymeleaf template, etc.).@Controller
-annotated class to return a raw response (like JSON or XML), you'd use the @ResponseBody
annotation on that method. This annotation tells Spring to serialize the return value and send it in the response body.@Controller public class MyController { @RequestMapping("/greet") @ResponseBody public String greet() { return "Hello, World!"; } }
@RestController:
@Controller
that's intended for RESTful web services. Introduced in Spring 4.@RestController
will have @ResponseBody
semantics by default, meaning their return values will be automatically serialized to JSON/XML and returned in the response body.@RestController
, you're not returning views. If you need to return views, consider using @Controller
or a mix of both based on requirements.@RestController public class MyRestController { @RequestMapping("/greet") public String greet() { return "Hello, World!"; } }
@Controller
is used when you're creating a traditional web application with server-side view rendering. For methods that should return a data response instead of a view, the @ResponseBody
annotation is used.
@RestController
is used when you're building a RESTful API or any backend that returns data directly to the client (e.g., AJAX calls from a SPA - Single Page Application). With @RestController
, you don't need to use @ResponseBody
on each method; it's applied to all methods by default.
It's crucial to choose the appropriate annotation based on the type of response your application or specific endpoint is designed to produce.
Examples of @Controller
and @RestController
in Spring applications:
@Controller
:@Controller public class MyController { @GetMapping("/hello") public String sayHello() { return "hello"; } }
@RestController
:@RestController public class MyRestController { @GetMapping("/hello") public String sayHello() { return "hello"; } }
In the @RestController
example, the return value "hello" is directly sent as the response content, without rendering a view.