Video in progress
What is the difference between @RestController and @Controller?
@RestController = @Controller + @ResponseBody: the object a method returns is written straight into the response as JSON. A plain @Controller usually returns a template (view) name.
📖 Answer
@Controller
public class PageController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("name", "Ali");
return "index"; // renders templates/index.html
}
}
@RestController
public class UserApi {
@GetMapping("/api/users/{id}")
public UserDto get(@PathVariable long id) {
return service.find(id); // returned as JSON
}
}
You can return JSON from a @Controller too — you put @ResponseBody on the method. @RestController applies that to every method for you.
Conversion to JSON is done by an HttpMessageConverter; in Boot the default is Jackson. If the client asks for another format in the Accept header and there's a converter for it, the response goes out in that format.
Sign up to mark studied questions and save your progress.