Basic Spring Boot Controller Class Annotations
Basic Spring Boot Controller Class Annotations
Overview of Dispatcher Servlet
When a user hits an API (e.g., a GET call to fetch a user), the Dispatcher Servlet uses Handler Mapping to identify the appropriate controller to handle the request.
Key Annotations for Handler Mapping
@Controller
Indicates that the class is responsible for handling incoming HTTP requests.
@RestController
Similar to @Controller
, but it combines @Controller
and @ResponseBody
.
Difference Between @Controller and @RestController
@Controller
requires @ResponseBody
on each method, while @RestController
automatically applies it to all methods.
Request Mapping
To map APIs to controller methods, we use the @RequestMapping
annotation.
Example:
@RequestMapping("/api/v1")
public class SampleController {
@GetMapping("/fetchUser ")
public String getUser Details() {
// Logic to fetch user details
}
}
Simplified Mapping Annotations
@GetMapping
and @PostMapping
are shortcuts for @RequestMapping
with specific HTTP methods.
Request Parameters
@RequestParam
binds request parameters to method parameters.
@GetMapping("/fetchUser ")
public String getUser Details(@RequestParam String firstName, @RequestParam(required = false) String lastName) {
// Logic to fetch user details
}
Type Conversion
Spring Boot automatically performs type conversion from request parameters to method parameter types.
Path Variables
@PathVariable
is used to extract values from the URL path.
@GetMapping("/fetchUser /{id}")
public String getUser ById(@PathVariable String id) {
// Logic to fetch user by ID
}
Request Body
@RequestBody
binds the body of the HTTP request (typically JSON or XML) to a Java object.
@PostMapping("/saveUser ")
public ResponseEntity saveUser (@RequestBody User user) {
// Logic to save user
}
Response Entity
ResponseEntity
represents the entire HTTP response, including status, headers, and body.
@GetMapping("/fetchUser ")
public ResponseEntity getUser Details() {
return ResponseEntity.ok("User details fetched successfully");
}
Conclusion
In this session, we covered various annotations used in Spring Boot for handling HTTP requests and responses.
Comments
Post a Comment