Controller vs RestController in Spring Boot

By | September 20, 2024

The Controller and RestController in the Spring framework are both used to handle the HTTP requests, but they have a difference in their intended use and their behaviour.

Difference between Controller and RestController

ControllerRestController
The controller in Spring typically handles the traditional web requests and produces the HTML views.RestContoller is specifically designed to handle the Restful web services.
Methods of the controller class return a string value representing a “view” that will be further resolved by view-resolver to populate the JSP pages.The methods of the RestContoller return the RESTful data in the form of JSON or XML.
It is suitable for the application where the end user or the client expects to receive the HTML or JSP pages.RestControllers are suitable for the application where the client expects RESTful data as a response. 
Typically used in MVC (Model-View-Contoller) architecture.It is commonly used in the RESTful applications where the views are not part of the backend system.
Example: e-commerce websites where the servers need to render the HTML pages to be displayed in browsers.Example: Mobile banking apps where the clients need to interact with the servers to check account balances, fund transfers, etc.

When to use Controller vs RestController

  • Use of Controller
    • Developing web application where the user expects to receive HTML views (server-side rendering)
    • Applications using JSP, Thymeleaf or similar templates.
    • Working on traditional MVC applications that rely on the page reloads.
Java
@Controller
public class ProductController {

    @GetMapping("/product/{id}")
    public String showProductPage(@PathVariable Long id, Model model) {
        Product product = productService.findProductById(id);
        model.addAttribute("product", product);
        return "product-details";  // Refers to an HTML page "product-details.html"
    }
}
  • Use of RestController
    • While develoing RESTful web service or APIs where client consumes data in form of JSON or XML.
    • When we need to expose our backend services to be used by front-end frameworks (Angular/React), mobile apps or other systems.
    • Working with microservices or APIs that interacts with other services in a microservice architecture.
Java
@RestController
@RequestMapping("/api/accounts")
public class AccountController {

    @GetMapping("/{id}")
    public ResponseEntity<Account> getAccountById(@PathVariable Long id) {
        Account account = accountService.findAccountById(id);
        if (account != null) {
            return new ResponseEntity<>(account, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *