如何在 Spring Boot@ResponseBody 中返回404响应状态-方法返回类型是 Response?

我使用 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());
}

我尝试了一些典型的方法:

SetStatus (HttpStatus.NOT _ FOUND.value ()) ;
新响应实体(HttpStatus.BAD _ REQUEST) ;

但我需要返回 回应

如果视频为空,如何返回这里的404状态码?

145542 次浏览

Create a NotFoundException class with an @ResponseStatus(HttpStatus.NOT_FOUND) annotation and throw it from your controller.

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "video not found")
public class VideoNotFoundException extends RuntimeException {
}

Your original method can return ResponseEntity (doesn't change your method behavior):

@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
public ResponseEntity getData(@PathVariable(ID_PARAMETER) long id, HttpServletResponse res{
...
}

and return the following:

return new ResponseEntity(HttpStatus.NOT_FOUND);

You can just set responseStatus on res like this:

@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
...
}

This is very simply done by throwing org.springframework.web.server.ResponseStatusException:

throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "entity not found"
);

It's compatible with @ResponseBody and with any return value. Requires Spring 5+