Skip to content

Commit 50fad9e

Browse files
committed
Lenient port handling in HierarchicalUriComponents#toUriString
Closes gh-32003
1 parent 2b4ffe0 commit 50fad9e

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

Diff for: spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -485,7 +485,7 @@ public String toUriString() {
485485
if (this.host != null) {
486486
uriBuilder.append(this.host);
487487
}
488-
if (getPort() != -1) {
488+
if (StringUtils.hasText(this.port) && !this.port.equals("-1")) {
489489
uriBuilder.append(':').append(this.port);
490490
}
491491
}

Diff for: spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java

+6-6
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,12 @@ void toUriWithIpv6HostAlreadyEncoded() {
101101
URI.create("http://[1abc:2abc:3abc::5ABC:6abc]:8080/hotel%20list/Z%C3%BCrich"));
102102
}
103103

104+
@Test
105+
void toUriStringWithPortVariable() {
106+
String url = "http://localhost:{port}/first";
107+
assertThat(UriComponentsBuilder.fromUriString(url).build().toUriString()).isEqualTo(url);
108+
}
109+
104110
@Test
105111
void expand() {
106112
UriComponents uri = UriComponentsBuilder.fromUriString("https://example.com").path("/{foo} {bar}").build();
@@ -166,12 +172,6 @@ private void assertExceptionsForInvalidPort(UriComponents uriComponents) {
166172
assertThatIllegalStateException()
167173
.isThrownBy(uriComponents::toUri)
168174
.withMessage("The port must be an integer: XXX");
169-
assertThatIllegalStateException()
170-
.isThrownBy(uriComponents::toUriString)
171-
.withMessage("The port must be an integer: XXX");
172-
assertThatIllegalStateException()
173-
.isThrownBy(uriComponents::toString)
174-
.withMessage("The port must be an integer: XXX");
175175
}
176176

177177
@Test

0 commit comments

Comments
 (0)