Using UriComponentsBuilder.cloneBuilder does not copy uriVariables
See original GitHub issueAccording to the docs, when you do UriComponentsBuilder.cloneBuilder
(v5.2.5.RELEASE
) it should create a deep clone:
https://github.com/spring-projects/spring-framework/blob/c08e31b7d613bf91cbe2beac2dad66714403faee/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java#L146-L162
However, if your builder has pathSegment
s the uriVariables
will not be preserved.
Imagine the following scenario - you have a base
builder which you are going to receive and you need to append path(s) to it. Here is an oversimplified example:
public UriComponentsBuilder getStorageBuilder(int userId, String storageName) {
HashMap<String, Object> uriVariables = new HashMap<>();
uriVariables.put("userId", userId);
uriVariables.put("storageId", storageName);
UriComponentsBuilder baseBuilder = ServletUriComponentsBuilder.fromCurrentRequest();
baseBuilder.replacePath("/storages");
baseBuilder.pathSegment("{userId}");
baseBuilder.pathSegment("{storageName}");
baseBuilder.uriVariables(uriVariables);
return baseBuilder;
}
....
// Receive a configured `builder` (something else calls `getStorageBuilder` before this method and it's passed as an argument here)
public UriComponentsBuilder getStorageDirectoryListing(UriComponentsBuilder baseBuilder, String path) {
// http://localhost/storages/%7BuserId%7D/%7BstorageName%7D/some/path
return baseBuilder.cloneBuilder().path(path).toUriString();
}
In this case the cloned
builder will not have the uriVariables
copied. Furthermore, there is no getter
method for the uriVariables
so you can’t manually copy them. A quick’n’dirty workaround to this is would be:
String fileUrl = UriComponentsBuilder.fromUriString(baseBuilder.toUriString())
.path("/some/path").build().toUriString();
Unfortunately this removes the ability to change anything in the pathSegments
.
Is there anything I’m missing here for uriVariables
to be excluded when cloning or is this simply missing at the moment?
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:5 (4 by maintainers)
Top GitHub Comments
It seems that #21565 introduced that
uriVariables
field in 5.0.8 but didn’t include it in the cloning step. Let’s backport this fix to 5.1.x and 5.0.x as well in order to close that gap in all affected branches.It looks like it’s simply missing.