Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a dynamic URL in Spring MVC?

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?

like image 776
John Maclein Avatar asked May 29 '15 07:05

John Maclein


2 Answers

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();
like image 52
Neil McGuigan Avatar answered Oct 21 '22 04:10

Neil McGuigan


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.

like image 34
Grigory Avatar answered Oct 21 '22 05:10

Grigory