如何手动创建Spring Data Rest实体响应格式

时间:2016-05-30 09:51:21

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

我使用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"
        }
    } 
}

1 个答案:

答案 0 :(得分:1)

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

它应该是这样的:

@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