Junior — Middle
What is the difference between using @Controller and @RestController annotations in Spring?
sobes.tech AI
Answer from AI
The @Controller annotation in Spring is used to designate a class as an MVC controller that handles HTTP requests and returns the name of a view, such as a JSP or Thymeleaf template.
@RestController is a specialized annotation that combines @Controller and @ResponseBody. It indicates that the controller methods return data directly in the HTTP response body, usually in JSON or XML format, without using views.
Example:
@RestController
public class ApiController {
@GetMapping("/api/data")
public Data getData() {
return new Data("value"); // will be automatically serialized to JSON
}
}
@Controller
public class WebController {
@GetMapping("/page")
public String getPage(Model model) {
model.addAttribute("attr", "value");
return "pageView"; // name of the template for rendering
}
}
Thus, @RestController is convenient for creating REST APIs, while @Controller is used for web applications with server-side HTML generation.