如何在Spring MVC中构建动态URL?

17

我想发送一个URL,这个URL是基于一些动态值生成的。但我不想硬编码它,也不想使用response或request对象。

例如:

http://localhost:8585/app/image/{id}/{publicUrl}/{filename}

所以我只想从Spring Framework中获取第一部分(即http://localhost:8585/app/image)。我将提供其余的信息,如idpublicUrlfilename,以便生成一个完整的绝对URL。

在Spring MVC中如何实现?

3个回答

28
你是想监听一个URL还是构建一个外部使用的URL呢?
如果是后者,你可以使用URIComponentsBuilder在Spring中构建动态URL。例如:
UriComponents uri = UriComponentsBuilder
                    .fromHttpUrl("http://localhost:8585/app/image/{id}/{publicUrl}/{filename}")
                    .buildAndExpand("someId", "somePublicUrl", "someFilename");

String urlString = uri.toUriString();

2
不,我的问题是我不想硬编码“http://localhost:8585/app/”这一部分。现在我正在本地运行我的应用程序,所以它显示为“http://localhost:8585/”,而app是应用程序名称。如果我将此应用程序上传到例如www.example.com,并且我想使用example.com访问它。因此,我想提供“/image/{id}/{publicUrl}/{filename}”部分,其余部分将由Spring处理。 - John Maclein

8

这是对Neil McGuigan的回答的补充,但不需要硬编码模式、域、端口等...

可以这样做:

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

希望这有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接