【问题标题】:Spring data REST content negotiationSpring数据REST内容协商
【发布时间】:2016-04-09 17:40:28
【问题描述】:

我有一个带注释的 RepositoryRestResource 域对象,其字段也包含二进制数据(图像)。Spring Rest 机制将为这些字段创建漂亮的 RESTful 链接,但我还想介绍一个返回裸二进制文件的处理程序当浏览器发送“image/*”接受头时。

我可以在相同的路径上覆盖一个控制器,但它很脆弱,我宁愿为此编写一个策略类。

可能吗?知道将其插入 Spring 管道的何处吗?

TIA, 爱德华多

【问题讨论】:

  • 您是否考虑过不将控制器覆盖/重载到 // 端点,而只是添加另一个端点 //binary i>(或任何您认为合适的名称)返回资源的二进制数据?

标签: spring-data-rest


【解决方案1】:

“正确”使用 @RepositoryRestController 注释,您应该能够将控制器覆盖限制为仅“image/*”。

假设您有一个简单的域对象模型(getter/setter 和一些注释省略...)

public class Item {
    @Id
    private String id;
    private String name;
}

让我们只为 image/* 覆盖控制器

@RepositoryRestController
@ResponseBody
public class ItemRepositoryRestController {

    @Autowired
    private ItemRepository repository;

    @RequestMapping(value = "/items/{id}", method = RequestMethod.GET,
                    produces = "image/*")
    public Item getItem(@PathVariable(value = "id") String id)
    {
        Item item = repository.findOne(id);
        /* do some magic with your item */

        return item;
    }

很明显,这里没有返回 image/* 数据——实际上你会得到一个 400 错误——但你只有在询问是否接受 image/* em>,当且仅当您使用 @RequestMapping at the method level 时,在不请求 image/* 时通过 automagic Spring Rest Controller。

我还没有到返回原始二进制数据的地步,您可能必须直接使用 HttpServletResponse,如 here 所示。或者您可能已经对此有了答案,因为您在评论中提到已经添加了另一个资源路径(在这种情况下,我对您如何返回原始数据感兴趣)。

【讨论】:

  • 我接受了答案,尽管我现在在选择正确的生产子句时遇到了问题。我尝试的一切似乎都会导致 HTTP 406。
  • 如果您不发布代码示例,将无法进一步帮助您:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 2014-06-15
  • 2016-01-05
  • 2016-02-16
  • 2011-04-06
相关资源
最近更新 更多