我的 Controller 中有一个方法如下:
@RequestMapping(value = "/download/attachment/{attachmentId}", method = RequestMethod.GET)
public void download(@PathVariable("attachmentId") String attachmentId, HttpServletRequest request,
HttpServletResponse response) throws IOException {
InputStream file = myCustomObject.getAttachmentById(attachmentId);
response.setContentType("application/octet-stream");
response.flushBuffer();
}
我想使用 Spring 提供的 ControllerLinkBuilder 类生成指向此方法的模板化 HATEOAS 链接。我的链接应如下所示:
"download" : {
"href" : "https://localhost:8080/download/attachment/{attachmentId}"
}
我使用以下代码在我的 ResourceAssembler 类(扩展了 ResourceAssemblerSupport)中执行此操作:
Link downloadAttachmentLink = linkTo(MyRestController.class, MyRestController.class
.getMethod("download", String.class, HttpServletRequest.class, HttpServletResponse.class),
"{attachmentId}").withRel("download");
我从中得到的链接不是模板化的。它是 URL 编码的。 “{”作为 %7B 发送。我不希望这种事发生。有人可以建议什么吗?
最佳答案
好的,所以我使用以下方法解决了这个问题:
Link downloadAttachmentByIdLink = new Link(
new UriTemplate(
linkTo(MyRestController.class,
MyRestController.class.getMethod("download", String.class,
HttpServletRequest.class, HttpServletResponse.class),
"").toUriComponentsBuilder().build().toUriString(),
new TemplateVariables(
new TemplateVariable("attachmentId", TemplateVariable.VariableType.SEGMENT))),
"download");
关于java - Spring HATEOAS 模板链接无效下载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47064026/