如何在spring mvc中构建动态url

Joh*_*ein 8 java spring spring-mvc spring-data spring-data-rest

我试图发送一个我会根据一些动态值生成的URL.但我不想硬编码它也不想使用响应或请求对象.

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

所以我想 从Spring框架获得第一部分,即http:// localhost:8585/app/image /.我将提供其他的东西,如id,publicUrl,filename,以便它可以生成一个完整的绝对URL.

如何在Spring MVC中做到这一点.

我正在使用spring MVC,spring Data,Spring Rest,Hibernate.

Nei*_*gan 12

您是在尝试侦听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();
Run Code Online (Sandbox Code Playgroud)

  • 不,我的问题是我不想对“http://localhost:8585/app/”这部分进行硬编码。现在我正在本地运行我的应用程序,因此它显示“http://localhost:8585/”,app 是应用程序名称。如果我已上传此应用程序以显示 www.example.com 并且我想使用 example.com 访问该应用程序,该怎么办?所以我想提供“/image/{id}/{publicUrl}/{filename}”部分,其余部分将由 spring 处理。 (2认同)

Gri*_*ory 8

只是对 Neil McGuigan 的回答的补充,但没有硬编码模式、域、端口等......

可以这样做:

import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
...
ServletUriComponentsBuilder.fromCurrentRequest
        .queryParam("page", 1)
        .toUriString();
Run Code Online (Sandbox Code Playgroud)

想象一下最初的要求是

https://myapp.mydomain.com/api/resources
Run Code Online (Sandbox Code Playgroud)

此代码将生成以下 URL

https://myapp.mydomain.com/api/resources?page=1
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。