How to build a dynamic URL in Spring MVC?

John Maclein picture John Maclein · May 29, 2015 · Viewed 24k times · Source

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?

Answer

Neil McGuigan picture Neil McGuigan · May 29, 2015

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();