是否将位置标头添加到Spring MVC的POST响应中?

cdmah0mi  于 2023-02-13  发布在  Spring
关注(0)|答案(4)|浏览(122)

我的Sping Boot 1.4应用程序有这个POST方法来创建一个资源。作为一个要求,它应该给出一个指定新创建资源的URL的位置标头(https://www.rfc-editor.org/rfc/rfc9110.html#name-method-definitions)。我只是想知道除了手动构造URL并将其添加到响应中之外,是否还有什么好的方法来做到这一点。
如有任何帮助/线索,不胜感激

zi8p0yeb

zi8p0yeb1#

Building REST Services with Spring Guide中演示了这一确切场景。
持久化新实体后,可以在控制器中使用以下命令:

URI location = ServletUriComponentsBuilder
                    .fromCurrentRequest()
                    .path("/{id}")
                    .buildAndExpand(newEntity.getId())
                    .toUri();

然后,您可以使用ResponseEntity将其添加到您的响应中,如下所示:

ResponseEntity.created(location).build()

ResponseEntity.status(CREATED).header(HttpHeaders.LOCATION, location).build()

后者需要一个字符串,因此您可以在uri构建器上使用toUriString()而不是toUri()

kmb7vmvb

kmb7vmvb2#

@Autowired 
 private UserService service;

 @PostMapping("/users")
 public ResponseEntity<Object> createUser(@RequestBody User user)
  {
    User myUser = service.save(user);
    URI location = ServletUriComponentsBuilder
                .fromCurrentRequest()
                .path("/{id}")
                .buildAndExpand(myUser.getId())
                .toUri();

    ResponseEntity.created(location).build()
  }
myzjeezk

myzjeezk3#

另一种方法是使用UriComponentsBuilder,可以直接将其注入到控制器方法中:

@PostMapping(consumes = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public ResponseEntity<Void> addCustomer(
          UriComponentsBuilder uriComponentsBuilder, 
          @RequestBody CustomerRequest customerRequest ){

        final long customerId = customerService.addCustomer(customerRequest)

        UriComponents uriComponents =
                uriComponentsBuilder.path("/{id}").buildAndExpand(customerId);

        return ResponseEntity.created(uriComponents.toUri()).build();
}

请注意,下面的代码不会计算当前请求路径,您需要手动添加(否则可能会遗漏一些内容)。
例如:

UriComponents uriComponents =
       uriComponentsBuilder.path("CURRENT_REQUEST_PATH/{id}")
       .buildAndExpand(customerId);
wztqucjr

wztqucjr4#

这个answer为我指明了正确的方向,但是我创建实体的端点路径与保存实体的路径略有不同。
我可以像这样使用fromCurrentRequest()replacePath("new path here")

URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
        .replacePath("/customer/{id}/fat")
        .buildAndExpand(savedCustomer.getCustomerId())
        .toUri();

return ResponseEntity.created(uri).build();

相关问题