@Controller vs @RestController
1. @Controller
- @Controller tells Spring that this class contains web request handler methods.
- Marks a class as a Spring MVC controller.
- Handles web requests (GET/POST).
- Returns a view name(resolved by ViewResolver) instead of raw data.
- Used for web pages (MVC), not REST APIs.
- specialized forms of
@Component.
@Controller
public class HomeController {
@RequestMapping(path = "/home", method = RequestMethod.GET)
public String homePage() {
// This will be resolved to home.jsp or home.html
return "home";
}
}
2. @ResponseBody
- Tells Spring not to render a view, but instead Sends return value directly to HTTP response.
- Used for JSON, XML, or text.
- Can be applied to methods in a @Controller.
@Controller
public class UserController {
@RequestMapping(path = "/user", method = RequestMethod.GET)
@ResponseBody
public String userMessage() {
// This will return JSON (if Jackson is on the classpath)
return "message";
}
}
3. @RestController
A convenience annotation that combines: @Controller + @ResponseBody
- Every method automatically returns data (JSON/XML) instead of view.
- Commonly used for REST APIs.