Add ResponseEntity.of(Optional) variant
When dealing with `Optional` values in a Controller handler (for
example, values coming from a Spring Data repository), developers might
reuse this code snippet quite often:
```
@GetMapping("/user")
public ResponseEntity<Optional<User>> fetchUser() {
Optional<User> user = //...
return user.map(ResponseEntity::ok).orElse(notFound().build());
}
```
This commit adds a new static method on `ResponseEntity` for that,
simplifying the previous snippet with `return ResponseEntity.of(user);`
Note that in case more specific HTTP response headers are required by
the application, developers should use other static methods to
explicitly tell which headers should be used in each case.
Issue: SPR-17187
This commit is contained in:
@@ -19,6 +19,7 @@ package org.springframework.http;
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.lang.Nullable;
|
||||
@@ -213,6 +214,18 @@ public class ResponseEntity<T> extends HttpEntity<T> {
|
||||
return new DefaultBuilder(status);
|
||||
}
|
||||
|
||||
/**
|
||||
* A shortcut for creating a {@code ResponseEntity} with the given body
|
||||
* and the {@linkplain HttpStatus#OK OK} status, or an empty body and a
|
||||
* {@linkplain HttpStatus#NOT_FOUND NOT FOUND} status in case of a
|
||||
* {@linkplain Optional#empty()} parameter.
|
||||
* @return the created {@code ResponseEntity}
|
||||
* @since 5.1
|
||||
*/
|
||||
public static <T> ResponseEntity<T> of(Optional<T> body) {
|
||||
return body.map(ResponseEntity::ok).orElse(notFound().build());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a builder with the status set to {@linkplain HttpStatus#OK OK}.
|
||||
* @return the created builder
|
||||
|
||||
Reference in New Issue
Block a user