【问题标题】:How to create Spring Data Rest entities response format manually [duplicate]如何手动创建 Spring Data Rest 实体响应格式 [重复]
【发布时间】:2016-05-30 09:51:21
【问题描述】:

我正在使用 Spring Data Rest 创建一个 RESTful api。我想处理返回实体表示的异常,例如由 Spring Data Rest 存储库(带有 HATEOAS 链接)生成的实体表示。我需要返回实体表示的方法如下:

@ExceptionHandler(value = {ExistentUGVException.class})
@ResponseBody
protected ResponseEntity<UGV> existentUGVHandler(HttpServletRequest request, HttpServletResponse response, ExistentUGVException ex) {
    return new ResponseEntity<UGV>(ex.ugv, HttpStatus.OK);
}

此实现返回不带链接的 UGV 表示:

{
   "title" : "Golden Eagle Snatches Kid",
   "publishDate" : "2012-12-19T13:55:28Z",
   "url" : "https://www.youtube.com/watch?v=Xb0P5t5NQWM"
}

但它会是:

{
    "title" : "Golden Eagle Snatches Kid",
    "publishDate" : "2012-12-19T13:55:28Z",
    "url" : "https://www.youtube.com/watch?v=Xb0P5t5NQWM",
    "_links" : {
        "self" : {
            "href" : "http://localhost/youTubeVideos/Xb0P5t5NQWM"
        },
        "youTubeVideo" : {
            "href" : "http://localhost/youTubeVideos/Xb0P5t5NQWM{?projection}",
            "templated" : true
        },
        "user" : {
            "href" : "http://localhost/youTubeVideos/Xb0P5t5NQWM/user"
        }
    } 
}

【问题讨论】:

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


    【解决方案1】:

    您必须先将 ResponseEntity 转换为 Resource,然后手动添加链接。

    应该是这样的:

    @ExceptionHandler(value = {ExistentUGVException.class})
    @ResponseBody
    protected ResponseEntity<Resource<UGV>> existentUGVHandler(HttpServletRequest request, HttpServletResponse response, ExistentUGVException ex) {
        final Resource<UGV> resource = getResource(ex.ugv);
        return new ResponseEntity<Resource<UGV>>(resource, HttpStatus.OK);
    }
    
    public Resource<T> getResource(T object, Link... links) throws Exception {
        Object getIdMethod = object.getClass().getMethod("getId").invoke(object);
        Resource<T> resource = new Resource<T>(object); // The main resource
        final Link selfLink = entityLinks.linkToSingleResource(object.getClass(), getIdMethod).withSelfRel();
        String mappingRel = CLASSMAPPING.getMapping(this.getClass());
        final Link resourceLink = linkTo(this.getClass()).withRel(mappingRel);
        resource.add(selfLink, resourceLink);
        resource.add(links);
        return resource;
    }
    

    看看这里,这里有你需要的一切:spring hateoas documentation

    【讨论】:

    • 虽然理论上这可以回答这个问题,it would be preferable 在这里包含答案的基本部分,并提供链接以供参考。
    • 我已经修改了答案以提供示例代码
    • 很高兴看到您编辑了您的帖子。
    猜你喜欢
    • 2017-02-22
    • 1970-01-01
    • 2017-01-06
    • 2015-10-03
    • 2017-01-18
    • 2017-12-05
    • 2011-12-02
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多