diff --git a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java index 83a4bbc7f2ff..ceb8f0d69c4a 100644 --- a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2023 the original author or authors. + * Copyright 2002-2024 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. @@ -485,7 +485,7 @@ public String toUriString() { if (this.host != null) { uriBuilder.append(this.host); } - if (getPort() != -1) { + if (StringUtils.hasText(this.port) && !this.port.equals("-1")) { uriBuilder.append(':').append(this.port); } } diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java index 809eca995b08..1415ab29c5ac 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java @@ -101,6 +101,12 @@ void toUriWithIpv6HostAlreadyEncoded() { URI.create("http://[1abc:2abc:3abc::5ABC:6abc]:8080/hotel%20list/Z%C3%BCrich")); } + @Test + void toUriStringWithPortVariable() { + String url = "http://localhost:{port}/first"; + assertThat(UriComponentsBuilder.fromUriString(url).build().toUriString()).isEqualTo(url); + } + @Test void expand() { UriComponents uri = UriComponentsBuilder.fromUriString("https://example.com").path("/{foo} {bar}").build(); @@ -166,12 +172,6 @@ private void assertExceptionsForInvalidPort(UriComponents uriComponents) { assertThatIllegalStateException() .isThrownBy(uriComponents::toUri) .withMessage("The port must be an integer: XXX"); - assertThatIllegalStateException() - .isThrownBy(uriComponents::toUriString) - .withMessage("The port must be an integer: XXX"); - assertThatIllegalStateException() - .isThrownBy(uriComponents::toString) - .withMessage("The port must be an integer: XXX"); } @Test