1. Introduction
In Spring Framework, @Controller and @RestController are annotations used to create web controllers. @Controller is used to mark a class as a web request handler, a part of Spring MVC that allows you to create views. @RestController combines @Controller and @ResponseBody, indicating that the return value of the methods should be bound to the web response body and is typically used for APIs.
2. Key Points
1. @Controller is a stereotype annotation indicating the class is a web controller.
2. @RestController is a specialized version of the controller that is a convenience annotation for creating RESTful controllers.
3. @Controller is typically used in combination with @ResponseBody or a view resolver for rendering views.
4. @RestController assumes every method returns a domain object instead of a view, which is directly written to the HTTP response as JSON or XML.
3. Differences
@Controller | @RestController |
---|---|
Used for creating MVC controllers. | Used for creating RESTful controllers. |
Methods can return a view name. | Methods return a domain object instead of a view. |
Requires @ResponseBody to indicate method response should be bound to the web response body. | Automatically binds method response to the web response body. |
4. Example
// Example using @Controller
@Controller
public class MyViewController {
@RequestMapping("/greeting")
public String getGreeting(Model model) {
model.addAttribute("message", "Hello World");
return "greeting"; // Name of the view
}
}
// Example using @RestController
@RestController
public class MyRestController {
@RequestMapping("/data")
public MyData getData() {
return new MyData("Hello World"); // Data is directly written as JSON
}
}
public class MyData {
private String message;
// Constructor and getter
}
Output:
// Output from @Controller would be the rendered view greeting. // Output from @RestController would be the JSON string: {"message":"Hello World"}
Explanation:
1. MyViewController with @Controller is a traditional Spring MVC controller that returns a view name to be resolved and rendered.
2. MyRestController with @RestController directly returns a MyData object that will be automatically converted to JSON format and sent in the response body.
5. When to use?
- Use @Controller when building a web application that renders HTML views.
- Use @RestController when developing a RESTful web service that returns data in a format such as JSON or XML for consumption by various clients.
Comments
Post a Comment
Leave Comment