Sobes.tech
Junior

What is the difference between RestController and Controller in Spring?

sobes.tech AI

Answer from AI

@Controller marks a class as a Spring MVC controller. This class typically returns view names, which are then processed by view resolvers to display the user interface (e.g., HTML pages). @Controller is often used for creating web applications with server-side rendering.

@RestController is a specialized version of @Controller. It automatically adds the @ResponseBody annotation to each method. This means that methods in @RestController by default return data (e.g., JSON or XML) rather than view names. @RestController is ideal for creating RESTful web services that provide data to clients (e.g., frontend applications or other services).

Main difference:

  • @Controller: Returns view names.
  • @RestController: Returns data (automatically adds @ResponseBody).

Example of @Controller:

@Controller
public class ViewController {

    @GetMapping("/hello")
    public String sayHello(Model model) {
        model.addAttribute("message", "Hello, world!");
        return "helloView"; // Returns view name
    }
}

Example of @RestController:

@RestController
public class DataController {

    @GetMapping("/data")
    public Map<String, String> getData() {
        Map<String, String> response = new HashMap<>();
        response.put("status", "success");
        response.put("message", "Data retrieved");
        return response; // Returns a Map that will be converted to JSON
    }
}