Junior — Middle
What is the difference between @Controller and @RestController annotations in Spring?
sobes.tech AI
Answer from AI
The @Controller annotation in Spring is used to designate a class as a controller in an MVC application. Methods of such a controller typically return the name of the view to be rendered.
The @RestController annotation is a specialized version of @Controller that automatically adds the @ResponseBody annotation to all methods of the class. This means that methods return data (usually in JSON or XML format) directly in the HTTP response body, rather than a view name.
Example:
@RestController
public class MyRestController {
@GetMapping("/api/data")
public MyData getData() {
return new MyData("value"); // will be serialized to JSON
}
}
@Controller
public class MyController {
@GetMapping("/page")
public String getPage() {
return "pageView"; // name of the template for rendering
}
}