Sobes.tech
Junior

How to create a controller in Spring?

sobes.tech AI

Answer from AI

Creating a controller in Spring can be done in several ways:

  1. Using the @Controller annotation: It is used to mark a class as a controller component, usually in conjunction with a view.

    // Example controller returning a view name
    package com.example.demo.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping("/greet") // Base path for this controller
    public class GreetingController {
    
        @GetMapping("/hello") // Handles GET requests to /greet/hello
        public String sayHello() {
            return "hello"; // Returns the view name (e.g., hello.html)
        }
    }
    
  2. Using the @RestController annotation: It combines the functionality of @Controller and @ResponseBody, meaning that the return value of methods is directly converted into a response format (e.g., JSON, XML) and sent to the client. It is often used for creating RESTful web services.

    // Example REST controller
    package com.example.demo.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class DataController {
    
        @GetMapping("/data") // Handles GET requests to /data
        public String getData() {
            return "{\"message\": \"This is test data\"}"; // Returns JSON
        }
    }
    
  3. Inheritance from abstract classes (deprecated approach): In earlier versions of Spring, inheritance from classes such as AbstractController or ServletForwardingController was used. This approach is considered outdated and less flexible compared to using annotations.

The most common and recommended way to create controllers in modern Spring applications is using @Controller and @RestController annotations. Spring automatically detects such classes in the classpath through component scanning and registers them as controllers.

To handle incoming requests, controller methods use annotations such as:

  • @RequestMapping: General for all HTTP methods.
  • @GetMapping: For GET requests.
  • @PostMapping: For POST requests.
  • @PutMapping: For PUT requests.
  • @DeleteMapping: For DELETE requests.
  • @PatchMapping: For PATCH requests.

Understanding the execution flow:

  1. The client sends an HTTP request.
  2. Spring's DispatcherServlet intercepts the request.
  3. Based on the URL, DispatcherServlet finds the corresponding method in the controller using @RequestMapping annotations and its derivatives.
  4. The controller method processes the request, performing necessary logic (e.g., calling services or repositories).
  5. If @Controller is used, the method returns a logical view name. DispatcherServlet uses ViewResolver to determine the actual view (e.g., an HTML file).
  6. If @RestController is used, the method's return value is converted into a response format (e.g., JSON) and sent directly to the client.