Junior
What is the difference between @Controller and @RestController in Spring Framework?
sobes.tech AI
Answer from AI
@Controller is used to mark a class as a controller component in the Spring MVC architecture. It is often used for handling web requests and returning ModelAndView or view names.
@RestController is a specialized version of @Controller. It combines @Controller and @ResponseBody, indicating that the return values of methods should be automatically converted into a format suitable for HTTP responses (e.g., JSON or XML). It is most commonly used for creating RESTful web services.
Main differences:
@Controller: ReturnsModelAndViewor a view name, which is then processed by a view resolver.@RestController: Returns data directly (by default in JSON/XML), which is sent back to the client. No need for@ResponseBodyon each method.
Example:
// Using @Controller
@Controller
public class ViewController {
@GetMapping("/view")
public String showView() {
return "myview"; // Returns the view name
}
}
// Using @RestController
@RestController
public class RestDataController {
@GetMapping("/data")
public MyData getData() {
return new MyData("Hello", "World"); // Returns data that is converted to JSON
}
static class MyData {
private String field1;
private String field2;
public MyData(String field1, String field2) {
this.field1 = field1;
this.field2 = field2;
}
public String getField1() { return field1; }
public String getField2() { return field2; }
}
}