【问题标题】:Spring HATEOAS Link with Matrix Variable Not Working带有矩阵变量的 Spring HATEOAS 链接不起作用
【发布时间】:2016-01-18 08:33:58
【问题描述】:

我正在尝试从 Spring MVC 控制器生成并添加指向 RESTful 资源的链接。我们的 API 需要使用 HTTP 矩阵变量。不幸的是,生成的自链接缺少 URI 中的矩阵变量。

@BasePathAwareController
@RequestMapping("/licenses")
public class LicenseController {

  @Autowired
  private LicenseRepository repository;

  @RequestMapping(path = "/{licenseId}/violations", method = RequestMethod.GET)
  @RestResource(rel = "violations")
  @ResponseBody
  @Transactional(readOnly = true)
  public ResponseEntity<?> getViolations(@PathVariable String licenseId, @MatrixVariable(name = "state") String state) {
    try {
      StateContextHolder.setState(state);
      List<ViolationEntity> violations = repository.findOne(licenseId).getViolations();

      if (violations == null) {
        return new ResponseEntity<Resources<?>>(HttpStatus.OK);
      }
      else {
        Resources<?> entityResource = new Resources(violations);
        entityResource.add(linkTo(methodOn(LicenseController.class).getViolations(licenseId, state)).withSelfRel());

        return new ResponseEntity<Resources<?>>(entityResource, HttpStatus.OK);
      }
    }
    finally {
      StateContextHolder.clear();
    }

  }
}

对于 HTTP GET /licenses/123456789;state=NY/violations,返回的 self 链接缺少状态矩阵参数:

{
  ...,
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/licenses/123456789/violations"
    }
  }
}

我不想硬编码,所以我想弄清楚如何使用 Spring HATEOAS 或 Spring Data REST API 来做到这一点。

我需要使用矩阵参数来优化许可证路径元素。你可以阅读更多关于为什么here。可以这么说,在 Spring Data 从存储库中检索实体之前,我们正在执行一些自定义行为。

【问题讨论】:

  • “我需要使用矩阵参数来优化许可证路径元素” - 假设存在许可证资源并且许可证 ID 在各州之间不是唯一的,那么 @987654324 @作为一个整体是一个关键。没有细化。 FWIW,您可以尝试 /{licenseId};state={state}/violationsstate 作为路径变量。

标签: spring-data spring-data-rest spring-hateoas


【解决方案1】:

在我看来,Spring HATEOAS 目前不支持矩阵参数。

  1. 请参阅UriTemplate 的这一部分。它使用不同的变量类型来构建 Uri。矩阵参数不是其中之一。
  2. 查看VariableType 枚举,它用于打开开关。也没有矩阵参数。

【讨论】:

  • 我在 Spring HATEOS 项目中打开了this issue
猜你喜欢
  • 1970-01-01
  • 2012-11-08
  • 2016-04-14
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
相关资源
最近更新 更多