Custom Spring MVC HTTP Patch requests with Spring Data Rest functionality

做~自己de王妃 提交于 2019-11-30 05:21:40

问题


What is the best practice for supporting HTTP PATCH in custom Spring MVC controllers? Particularly when using HATEOAS/HAL? Is there an easier way to merge objects without having to check for the presence of every single field in the request json (or writing and maintaining DTOs), ideally with automatic unmarshalling of links to resources?

I know this functionality exists in Spring Data Rest, but is it possible to leverage this for use in custom controllers?


回答1:


I do not think you can use the spring-data-rest functionality here.

spring-data-rest is using json-patch library internally. Basically I think the workflow would be as follows:

  • read your entity
  • convert it to json using the objectMapper
  • apply the patch (here you need json-patch) (I think your controller should take a list of JsonPatchOperation as input)
  • merge the patched json into your entity

I think the hard part is the fourth point. But if you do not have to have a generic solution it could be easier.

If you want to get an impression of what spring-data-rest does - look at org.springframework.data.rest.webmvc.config.JsonPatchHandler

EDIT

The patch mechanism in spring-data-rest changed significantly in the latest realeases. Most importantly it is no longer using the json-patch library and is now implementing json patch support from scratch.

I could manage to reuse the main patch functionality in a custom controller method.

The following snippet illustrates the approach based on spring-data-rest 2.6

        import org.springframework.data.rest.webmvc.IncomingRequest;
        import org.springframework.data.rest.webmvc.json.patch.JsonPatchPatchConverter;
        import org.springframework.data.rest.webmvc.json.patch.Patch;

        //...
        private final ObjectMapper objectMapper;
        //...

        @PatchMapping(consumes = "application/json-patch+json")
        public ResponseEntity<Void> patch(ServletServerHttpRequest request) {
          MyEntity entityToPatch = someRepository.findOne(id)//retrieve current state of your entity/object to patch

          Patch patch = convertRequestToPatch(request);
          patch.apply(entityToPatch, MyEntity.class);

          someRepository.save(entityToPatch);
          //...
        }      

        private Patch convertRequestToPatch(ServletServerHttpRequest request) {  
          try {
            InputStream inputStream =  new IncomingRequest(request).getBody();
            return new JsonPatchPatchConverter(objectMapper).convert(objectMapper.readTree(inputStream));
          } catch (IOException e) {
            throw new UncheckedIOException(e);
          }
        }


来源:https://stackoverflow.com/questions/33288670/custom-spring-mvc-http-patch-requests-with-spring-data-rest-functionality

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