How to create a controller in Spring?
sobes.tech AI
Answer from AI
Creating a controller in Spring can be done in several ways:
-
Using the
@Controllerannotation: 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) } } -
Using the
@RestControllerannotation: It combines the functionality of@Controllerand@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 } } -
Inheritance from abstract classes (deprecated approach): In earlier versions of Spring, inheritance from classes such as
AbstractControllerorServletForwardingControllerwas 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:
- The client sends an HTTP request.
- Spring's DispatcherServlet intercepts the request.
- Based on the URL, DispatcherServlet finds the corresponding method in the controller using
@RequestMappingannotations and its derivatives. - The controller method processes the request, performing necessary logic (e.g., calling services or repositories).
- If
@Controlleris used, the method returns a logical view name. DispatcherServlet uses ViewResolver to determine the actual view (e.g., an HTML file). - If
@RestControlleris used, the method's return value is converted into a response format (e.g., JSON) and sent directly to the client.