Spring MVC HTTP Custom Requests with Spring Data Rest Features

What is the best practice for supporting HTTP PATCH in Spring MVC custom controllers? In particular, when using HATEOAS / HAL? Is there an easier way to combine objects without having to check for each individual field in a json request (or write and maintain a DTO), ideally with automatically decoupling resource references?

I know that this functionality exists in Spring Data Rest, but can it be used for use in user controllers?

+4
source share
1 answer

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

spring -data-rest uses the json-patch internal library. Basically, I think the workflow will be as follows:

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

I think the hard part is the fourth point. But if you don’t need to have a general solution, it might be easier.

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

EDIT

The fix mechanism in spring -data-rest has changed significantly in recent versions. Most importantly, it no longer uses the json-patch library and now uses the json patch from scratch.

I would be able to reuse the main features of the patch in the user controller method.

The following snippet illustrates an 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); } } 
+8
source

Source: https://habr.com/ru/post/1268403/


All Articles