Card 04/ 06

GotchaDifficulty: Intermediate1 min

@RestController vs @Controller

Two methods, identical bodies, both returning the string "hello". One answers with hello. The other 404s.

java
@RestController
class GreetingRestController {
    @GetMapping("/rest-greeting")
    String greet() { return "hello"; }
}

@Controller
class GreetingViewController {
    @GetMapping("/view-greeting")
    String greet() { return "hello"; }
}
text
@RestController -> 200 body="hello"
@Controller -> 404 (treats "hello" as a view name to resolve)
run in a container — identical method bodies, different class annotation

@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.