【问题标题】:How to build a dynamic URL in Spring MVC?如何在 Spring MVC 中构建动态 URL?
【发布时间】:2015-08-11 23:07:21
【问题描述】:

我正在尝试发送一个我将根据一些动态值生成的 URL。但我不想硬编码,也不想使用响应或请求对象。

例子:

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

所以我想得到第一部分(即http://localhost:8585/app/image) 仅来自 Spring 框架。我将提供诸如idpublicUrlfilename 之类的其余内容,以便它可以生成完整的绝对 URL。

在 Spring MVC 中如何实现?

【问题讨论】:

    标签: java spring spring-mvc spring-data spring-data-rest


    【解决方案1】:

    您是在尝试侦听 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();
    

    【讨论】:

    • 不,我的问题是我不想硬编码“localhost:8585/app”这部分。现在我在本地运行我的应用程序,因此它显示“localhost:8585”,app 是应用程序名称。如果我已将此应用程序上传为 www.example.com 并且我想使用 example.com 访问它怎么办。所以我想提供“/image/{id}/{publicUrl}/{filename}”部分,其余部分将在春天处理。
    【解决方案2】:

    只是对 Neil McGuigan 的 answer 的补充,但没有硬编码架构、域、端口 & 等...

    可以这样做:

    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
    

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      • 2012-08-17
      相关资源
      最近更新 更多