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:
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2016 the original author or authors.
|
||||
* Copyright 2002-2018 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -19,6 +19,7 @@ package org.springframework.http;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
@@ -72,6 +73,25 @@ public class ResponseEntityTests {
|
||||
assertEquals(entity, responseEntity.getBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ofOptional() {
|
||||
Integer entity = 42;
|
||||
ResponseEntity<Integer> responseEntity = ResponseEntity.of(Optional.of(entity));
|
||||
|
||||
assertNotNull(responseEntity);
|
||||
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
|
||||
assertEquals(entity, responseEntity.getBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ofEmptyOptional() {
|
||||
ResponseEntity<Integer> responseEntity = ResponseEntity.of(Optional.empty());
|
||||
|
||||
assertNotNull(responseEntity);
|
||||
assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
|
||||
assertNull(responseEntity.getBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createdLocation() throws URISyntaxException {
|
||||
URI location = new URI("location");
|
||||
|
||||
Reference in New Issue
Block a user