具有Spring数据Rest功能的自定义Spring MVC HTTP修补程序请求
在定制SpringMVC控制器中支持HTTP补丁的最佳实践是什么?尤其是在使用HATEOAS/HAL时?有没有一种更简单的方法可以合并对象,而不必检查请求json中是否存在每个字段(或编写和维护DTO),理想情况下是自动解组到资源的链接具有Spring数据Rest功能的自定义Spring MVC HTTP修补程序请求,spring,spring-mvc,spring-boot,spring-data-rest,spring-hateoas,Spring,Spring Mvc,Spring Boot,Spring Data Rest,Spring Hateoas,在定制SpringMVC控制器中支持HTTP补丁的最佳实践是什么?尤其是在使用HATEOAS/HAL时?有没有一种更简单的方法可以合并对象,而不必检查请求json中是否存在每个字段(或编写和维护DTO),理想情况下是自动解组到资源的链接 我知道SpringDataREST中存在此功能,但是否可以在自定义控制器中使用此功能 我认为您不能在这里使用spring数据rest功能 SpringDataREST在内部使用库。基本上,我认为工作流程如下: 阅读你的实体 使用objectMapper将其转换
我知道SpringDataREST中存在此功能,但是否可以在自定义控制器中使用此功能 我认为您不能在这里使用spring数据rest功能 SpringDataREST在内部使用库。基本上,我认为工作流程如下:
- 阅读你的实体
- 使用objectMapper将其转换为json
- 应用补丁(这里您需要json补丁)(我认为您的控制器应该将JSONPATCH操作列表作为输入)
- 将修补的json合并到实体中
org.springframework.data.rest.webmvc.config.JsonPatchHandler
编辑
SpringDataREST中的补丁机制在最近几年发生了显著变化。最重要的是,它不再使用json补丁库,而是从头开始实现json补丁支持
我可以设法在自定义控制器方法中重用主修补程序功能
下面的代码片段演示了基于SpringDataREST2.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);
}
}
import org.springframework.data.rest.webmvc.IncomingRequest;
导入org.springframework.data.rest.webmvc.json.patch.jsonpatchconverter;
导入org.springframework.data.rest.webmvc.json.patch.patch;
//...
私有最终ObjectMapper ObjectMapper;
//...
@补丁映射(consumes=“application/json patch+json”)
公共响应性修补程序(ServletServerHttpRequest请求){
MyEntity entityToPatch=someRepository.findOne(id)//检索要修补的实体/对象的当前状态
补丁补丁=convertRequestToPatch(请求);
patch.apply(entityToPatch,MyEntity.class);
someRepository.save(entityToPatch);
//...
}
专用修补程序convertRequestToPatch(ServletServerHttpRequest请求){
试一试{
InputStream InputStream=新入职请求(request).getBody();
返回新的JsonPatchConverter(objectMapper.convert(objectMapper.readTree(inputStream));
}捕获(IOE异常){
抛出新的未选中异常(e);
}
}
谢谢!是的,我查过特别提款权的来源。不过,似乎这一功能的大部分可以从SDR本身中分离出来,以获得更通用的解决方案。这肯定会使手工制作HATEOAS兼容的自定义控制器变得更容易。当我尝试此操作时,我在objectMapper.readTree(inputStream)
处得到java.io.IOException:Stream closed
。知道为什么吗?我已经整理了一份报告,描述了在春季使用补丁的方法。上提供了一个工作示例。还可以查看其他可能的解决方案: