首页 > 解决方案 > spring webflux hatoas:如何使用主机映射获取完整链接

问题描述

我已经尝试实现 ReactiveRepresentationModelAssembler 但我得到的是相对链接而不是完整的端点。

    linkTo(methodOn(Controller.class).getInventories(exchange)).withRel("inventories").withType("application/hal+json")
    
    0   
    rel     "self"
    href    "/inventories/29956818123009640111752274638"
    type    "application/hal+json"

    1   
    rel     "inventories"
    href    "/inventories"
    type    "application/hal+json"

    2   
    rel     "patch"
    href    "/inventories"
    type    "application/hal+json"

我知道使用 SpringMvc,您可以获取 ServletContext 并在链接中配置 contextPath。使用 Spring WebFlux 我找不到方法。在实现 ReactiveRepresentationModelAssembler 的类中,在 toModel 方法 ServerWebExchange 中有一个新参数:

@Override
public Mono<InventoryResource> toModel(Inventory entity, ServerWebExchange exchange)

我没有使用这个我知道链接到请求、包含会话等的对象,并且我知道它可以作为方法参数添加到控制器中。我想我必须在 ReactiveRepresentationModelAssembler 类中构建仇恨链接的方法中使用这个对象。

我也尝试在 WebFluxConfigurationSupport 中配置 configurePathMatching 但 PathMatchConfigurer 的反应版本没有属性 setUrlPathHelper 我不能执行以下操作:

    UrlPathHelper pathHelper = new UrlPathHelper();
    pathHelper.setAlwaysUseFullPath(true);
    configurer.setUrlPathHelper(pathHelper)

有什么建议吗?我需要知道如何在 hatoas 链接中获取完整路径

   http://localhost:8080/inventories

PS:我已经设法从 ServerWebExchange 获取主机:

        InetSocketAddress host = exchange.getRequest().getHeaders().getHost(); // = localhost:8080

标签: spring-bootspring-webfluxspring-hateoas

解决方案


推荐阅读