Sobes.tech
Junior

What is the difference between RestController and Controller in Spring?

sobes.tech AI

Answer from AI

@RestController is a specialized version of @Controller that combines @Controller and @ResponseBody.

Differences:

Feature @Controller @RestController
Purpose Used for web applications returning views (HTML). Used for creating RESTful web services returning data (JSON, XML).
@ResponseBody Requires explicit use on each method or class to return data instead of a view. Includes @ResponseBody by default for all methods returning data.
Return value Usually returns a view name (String), processed by view resolver for HTML display. Usually returns a Java object, converted to JSON or XML via message converter.

Example of @Controller:

// Example Controller returning a view
@Controller
@RequestMapping("/view")
public class ViewController {

    @GetMapping("/greeting")
    public String showGreetingPage(Model model) {
        model.addAttribute("message", "Hello, world!");
        return "greeting"; // View name
    }
}

Example of @RestController:

// Example RestController returning JSON
@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        // Logic to get user from DB
        return new User(id, "Ivan"); // Spring converts to JSON
    }
}