【问题标题】:How to build a dynamic URL in Spring MVC?如何在 Spring MVC 中构建动态 URL?
【发布时间】:2015-08-11 23:07:21
【问题描述】:
【问题讨论】:
标签:
java
spring
spring-mvc
spring-data
spring-data-rest
【解决方案1】:
您是在尝试侦听 URL 还是尝试构建 URL 以供外部使用?
如果是后者,您可以使用URIComponentsBuilder 在 Spring 中构建动态 URL。示例:
UriComponents uri = UriComponentsBuilder
.fromHttpUrl("http://localhost:8585/app/image/{id}/{publicUrl}/{filename}")
.buildAndExpand("someId", "somePublicUrl", "someFilename");
String urlString = uri.toUriString();
【讨论】:
-
不,我的问题是我不想硬编码“localhost:8585/app”这部分。现在我在本地运行我的应用程序,因此它显示“localhost:8585”,app 是应用程序名称。如果我已将此应用程序上传为 www.example.com 并且我想使用 example.com 访问它怎么办。所以我想提供“/image/{id}/{publicUrl}/{filename}”部分,其余部分将在春天处理。
【解决方案2】:
只是对 Neil McGuigan 的 answer 的补充,但没有硬编码架构、域、端口 & 等...
可以这样做:
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
...
ServletUriComponentsBuilder.fromCurrentRequest
.queryParam("page", 1)
.toUriString();
想象最初的请求是
https://myapp.mydomain.com/api/resources
此代码将生成以下 URL
https://myapp.mydomain.com/api/resources?page=1
希望这会有所帮助。