Junior
What is the difference between RestController and Controller in Spring?
sobes.tech AI
Answer from AI
@Controller is used for handling HTTP requests in Spring MVC and typically returns the name of a view (e.g., JSP, Thymeleaf) to be rendered on the client. It works together with ViewResolver.
@RestController is a combination of @Controller and @ResponseBody. It indicates that the return value of a method should be directly converted into the body of the HTTP response. It is most commonly used for creating RESTful web services that return data in JSON or XML format.
Key differences:
- Return value:
@Controllerreturns the view name,@RestControllerreturns data. @ResponseBody:@RestControllerimplicitly includes@ResponseBodyfor all methods.- Purpose:
@Controlleris suitable for traditional web applications with server-side rendering,@RestControllerfor creating RESTful APIs.
Example of @Controller:
// Example Controller
@Controller
@RequestMapping("/web")
public class WebController {
@GetMapping("/hello")
public String sayHello() {
return "hello"; // Returns view name (e.g., hello.html)
}
}
Example of @RestController:
// Example RestController
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/hello")
public Map<String, String> sayHelloRest() {
Map<String, String> response = new HashMap<>();
response.put("message", "Hello from REST API!");
return response; // Returns JSON object
}
}