Card 04/ 06
All 6 cards
GotchaDifficulty: Intermediate1 min
@RestController vs @Controller
Two methods, identical bodies, both returning the string "hello". One answers with hello. The other 404s.
@RestController
class GreetingRestController {
@GetMapping("/rest-greeting")
String greet() { return "hello"; }
}
@Controller
class GreetingViewController {
@GetMapping("/view-greeting")
String greet() { return "hello"; }
}@RestController -> 200 body="hello"
@Controller -> 404 (treats "hello" as a view name to resolve)@Controller treats a returned String as the name of a view to render — in a real templated application, "hello" would resolve to hello.html or similar. With no view resolver configured, Spring has nothing to render "hello" into and answers 404.
@RestController is @Controller plus @ResponseBody on every method, which changes that interpretation entirely: the return value becomes the response body itself. It is why every card in this topic so far has used @RestController, not @Controller.