Java 如何在 Spring MVC 中构建动态 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30523536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to build a dynamic URL in Spring MVC?
提问by John Maclein
I am trying to send one URL which I will generate on basis of some dynamic value. But I don't want to hard code it nor want to use response or request object.
我正在尝试发送一个 URL,我将根据某个动态值生成该 URL。但我不想对其进行硬编码,也不想使用响应或请求对象。
Example:
例子:
http://localhost:8585/app/image/{id}/{publicUrl}/{filename}
http://localhost:8585/app/image/{id}/{publicUrl}/{filename}
So I want to get the first part (i.e. http://localhost:8585/app/image)
from Spring Framework only. I will provide rest of the things like id
, publicUrl
, filename
, so that it can generate a complete absoluteURL.
所以我只想从 Spring Framework获取第一部分(即http://localhost:8585/app/image)。我将提供诸如id
, publicUrl
, 之类的其余内容filename
,以便它可以生成完整的绝对URL。
How to do it in Spring MVC?
如何在 Spring MVC 中做到这一点?
回答by yas
Have a look on that one. "URI Template Patterns".
看看那个。“URI 模板模式”。
回答by Neil McGuigan
Are you trying to listen on a URL or trying to build a URL to use externally?
您是在尝试侦听 URL 还是尝试构建一个 URL 以供外部使用?
If the latter, you can use the URIComponentsBuilderto build dynamic URLs in Spring. Example:
如果是后者,您可以使用URIComponentsBuilder在 Spring 中构建动态 URL。例子:
UriComponents uri = UriComponentsBuilder
.fromHttpUrl("http://localhost:8585/app/image/{id}/{publicUrl}/{filename}")
.buildAndExpand("someId", "somePublicUrl", "someFilename");
String urlString = uri.toUriString();
回答by Grigory
Just an addition to Neil McGuigan's answerbut without hardcoding schema, domain, port & etc...
只是对 Neil McGuigan 的回答的补充,但没有硬编码模式、域、端口等......
One could do this:
可以这样做:
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
...
ServletUriComponentsBuilder.fromCurrentRequest.queryParam("page", 1).toUriString();
imagine original request was to
想象一下最初的要求是
https://myapp.mydomain.com/api/resources
this code will produce following url
此代码将产生以下网址
https://myapp.mydomain.com/api/resources?page=1
Hope this helps.
希望这可以帮助。