【发布时间】: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}/violations与state作为路径变量。
标签: spring-data spring-data-rest spring-hateoas