我正在使用 Spring Boot 和基于 @ResponseBody 的方法,如下所示:
@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
public @ResponseBody Response getData(@PathVariable(ID_PARAMETER) long id, HttpServletResponse res) {
Video video = null;
Response response = null;
video = videos.get(id - 1);
if (video == null) {
// TODO how to return 404 status
}
serveSomeVideo(video, res);
VideoSvcApi client = new RestAdapter.Builder()
.setEndpoint("http://localhost:8080").build().create(VideoSvcApi.class);
response = client.getData(video.getId());
return response;
}
public void serveSomeVideo(Video v, HttpServletResponse response) throws IOException {
if (videoDataMgr == null) {
videoDataMgr = VideoFileManager.get();
}
response.addHeader("Content-Type", v.getContentType());
videoDataMgr.copyVideoData(v, response.getOutputStream());
response.setStatus(200);
response.addHeader("Content-Type", v.getContentType());
}
我尝试了一些典型的方法:
res.setStatus(HttpStatus.NOT_FOUND.value());新的响应实体(HttpStatus.BAD_REQUEST);
但我需要返回 Response。
如果视频为空,如何在此处返回 404 状态码?
这很简单,只需抛出 org.springframework.web.server.ResponseStatusException
:
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "entity not found"
);
它与 @ResponseBody
和任何返回值兼容。需要 Spring 5+
使用 @ResponseStatus(HttpStatus.NOT_FOUND)
注释创建一个 NotFoundException
类并将其从您的控制器中抛出。
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "video not found")
public class VideoNotFoundException extends RuntimeException {
}
ResponseStatusException
直到 Spring 5 才添加; (2) NotFoundException
可用于被捕获或用于具有 @ExceptionHandler
的双栈 HTML UI。
@AroundAdvice
组件中使用 @ExceptionHandler
org.springframework.data.rest.webmvc.ResourceNotFoundException
已经用 @ResponseStatus(HttpStatus.NOT_FOUND)
注释
您的原始方法可以返回 ResponseEntity
(不会改变您的方法行为):
@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
public ResponseEntity getData(@PathVariable(ID_PARAMETER) long id, HttpServletResponse res{
...
}
并返回以下内容:
return new ResponseEntity(HttpStatus.NOT_FOUND);
您可以像这样在 res 上设置 responseStatus:
@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
public ResponseEntity getData(@PathVariable(ID_PARAMETER) long id,
HttpServletResponse res) {
...
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
// or res.setStatus(404)
return null; // or build some response entity
...
}