2015-05-29 55 views
1

我想发送一个我将基于一些动态值生成的url。但我不想硬编码它,也不想使用响应或请求对象。如何在春天建立一个动态网址mvc

例子: - http://localhost:8585/app/image/ {ID}/{publicUrl}/{文件名}

所以我想从仅Spring框架的第一部分,即http://localhost:8585/app/image/ 。我会提供其余的东西,如id,publicUrl,filename,以便它可以生成一个完整的绝对url。

如何在spring MVC中做到这一点。

我使用的是Spring MVC,Spring Data,Spring Rest,Hibernate。

回答

4

你想试听一个网址或试图建立一个外部使用的URL吗?

如果是后者,您可以使用URIComponentsBuilder在Spring中构建动态URL。例如:

UriCompoents uri = UriComponentsBuilder 
        .fromHttpUrl("http://localhost:8585/app/image/{id}/{publicUrl}/{filename}") 
        .buildAndExpand("someId", "somePublicUrl", "someFilename"); 

String urlString = components.toUriString(); 
+1

不是我的问题是我不想硬编码“http:// localhost:8585/app /”这部分。现在我在本地运行我的应用程序,所以它显示“http:// localhost:8585 /”,app是应用程序名称。如果我已经上传这个应用程序来说www.example.com,并且我想通过使用example.com访问这个应用程序。所以我想提供“/ image/{id}/{publicUrl}/{filename}”部分,其余部分将在春季处理。 –

0

只是一个除了尼尔·麦圭根的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 

希望这会有所帮助。