How to build a dynamic URL in Spring MVC?
Solution 1
Are you trying to listen on a URL or trying to build a URL to use externally?
If the latter, you can use the URIComponentsBuilder to build dynamic URLs in Spring. Example:
UriComponents uri = UriComponentsBuilder
.fromHttpUrl("http://localhost:8585/app/image/{id}/{publicUrl}/{filename}")
.buildAndExpand("someId", "somePublicUrl", "someFilename");
String urlString = uri.toUriString();
Solution 2
Just an addition to Neil McGuigan's answer but without hardcoding schema, domain, port &, etc...
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 the following URL
https://myapp.mydomain.com/api/resources?page=1
Hope this helps.
John Maclein
Updated on September 02, 2020Comments
-
John Maclein over 3 years
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.
Example:
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 absolute URL.How to do it in Spring MVC?