How to create Spring Data Rest entities response format manually [duplicate]

删除回忆录丶 提交于 2019-12-10 22:12:23

问题


I'm using Spring Data Rest to create a RESTful api. I want to handle an exception returning an entity representation like the ones generated by the Spring Data Rest repositories (with HATEOAS links). The method from where I need to return the entity representation is the following:

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

This implementation returns the UGV representation without links:

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

But it would be:

{
    "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:


You'll have to transform your ResponseEntity to Resource first and then add the links manually.

It should be something like this :

@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;
}

Take a look here, there's all you need : spring hateoas documentation



来源:https://stackoverflow.com/questions/37522621/how-to-create-spring-data-rest-entities-response-format-manually

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!