gpt4 book ai didi

java - 使用 spring @RestController 在 null 上返回 HTTP 204

转载 作者:IT老高 更新时间:2023-10-28 13:48:55 28 4
gpt4 key购买 nike

这将返回 200 OK,内容长度:0

@RestController
public class RepoController {
@RequestMapping(value = "/document/{id}", method = RequestMethod.GET)
public Object getDocument(@PathVariable long id) {
return null;
}

}

简单地说,我希望它返回 204 No Content on null。

有没有办法强制 spring-mvc/rest 在 null 而不是 200 时返回 204?我不想更改每个 rest 方法以返回 ResponseEntity 或类似的东西,只将 null 映射到 204

最佳答案

您可以使用 @ResponseStatus注解。这样您就可以拥有一个 void 方法,而不必构建 ResponseEntity。

@DeleteMapping(value = HERO_MAPPING)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long heroId) {
heroService.delete(heroId);
}

顺便说一句,当对象存在时返回 200,否则返回 204,这对于 API REST 设计来说有点不寻常。当未找到请求的对象时,通常会返回 404(未找到)。这可以使用 ControllerAdvice 来实现。

在 Spring REST 中,最好使用异常处理程序来处理异常,而不是使用逻辑来决定响应状态等。这是使用 @ControllerAdvice 注释的示例:http://www.jcombat.com/spring/exception-handling-in-spring-restful-web-service

关于java - 使用 spring @RestController 在 null 上返回 HTTP 204,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32396884/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com