Spring BootRequest & Response Handling
Spring Boot

Request & Response Handling

Handle HTTP requests and build proper API responses.

@RequestBody and @ResponseBody

@RequestBody: Binds the HTTP request body to a Java object (for POST/PUT) @ResponseBody: Writes the return value to the HTTP response body (included in @RestController)
Java
@PostMapping("/users")
public ResponseEntity<UserDto> createUser(@RequestBody @Valid UserDto dto) {
    UserDto created = userService.create(dto);
    URI location = URI.create("/api/users/" + created.getId());
    return ResponseEntity.created(location).body(created);
}

Query Parameters and Path Variables

Extract values from the URL:
Java
// Path Variable: /api/users/42
@GetMapping("/{id}")
public User getUser(@PathVariable("id") Long userId) { ... }

// Query Param: /api/users?page=0&size=10
@GetMapping
public Page<User> getUsers(
    @RequestParam(defaultValue = "0") int page,
    @RequestParam(defaultValue = "10") int size) { ... }