【发布时间】:2019-05-21 18:05:40
【问题描述】:
我正在使用带有 HATEOAS 版本 0.25 的 Spring Boot 版本 2.0.6。我正在使用一个资源汇编器,它利用ControllerLinkBuilder 来生成资源链接。但是,问题在于它会生成相对链接,如何将其配置为使用来自任一请求标头的host 和port 方案(该应用程序将在 dev、qa 和 prod 中作为 docker 容器运行)或运行时的配置属性它从IDE本地。
我得到尊重 X-Forwarded-Host 标头的链接
"_links": {
"self": {
"href": "http://something.io/data/api/customers"
}
}
如果我明确添加标题X-Forwarded-Host 并使用此代码生成自我链接
Link self = new Link(
ServletUriComponentsBuilder.fromRequestUri(request).buildAndExpand(pageable).toUri().toString(),
"self");
但是当在资源汇编器中我依赖来自ControllerLinkBuilder 的通常的linkTo 调用时,主机和端口不会在链接中呈现。
"_links": {
"self": {
"href": "/customers/1"
},
"customers": {
"href": "/customers"
},
"contact": {
"href": "/customers/1/contact"
}
}
控制器定义
@Slf4j
@RestController
@RequestMapping("/customers")
@ExposesResourceFor(Customer.class)
public class CustomerController {
}
和get方法
@GetMapping(produces = MediaTypes.HAL_JSON_VALUE)
public DeferredResult<ResponseEntity<Resources<Resource<Customer>>>> getAllCustomers(
@PageableDefault(page = 0, size = 20, sort = "name", direction = Direction.ASC) Pageable pageable,
PagedResourcesAssembler<Customer> assembler, HttpServletRequest request) {
}
我在这里传递请求对象是因为linkTo 给出了一个没有主机和端口的 url
我正在使用客户资源汇编器from the code here,spring hateoas exmaples,它自动连接到这个控制器
@Autowired
private CustomerResourceAssember customerResourceAssembler;
这就是我调用分页资源汇编器的方式
assembler.toResource(result, customerResourceAssembler, self)
【问题讨论】:
标签: spring spring-mvc spring-boot spring-hateoas spring-web