Ich verwende Spring Boot mit @ResponseBody-basiertem Ansatz wie dem folgenden:
@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());
}
Ich habe einige typische Ansätze ausprobiert:
res.setStatus (HttpStatus.NOT_FOUND.value ());
neue ResponseEntity (HttpStatus.BAD_REQUEST);
aber ich muss zurückkehren Antwort .
Wie kann hier der Statuscode zurückgegeben werden, wenn das Video null ist?
Erstellen Sie eine NotFoundException
-Klasse mit einer @ResponseStatus(HttpStatus.NOT_FOUND)
-Anmerkung, und werfen Sie sie von Ihrem Controller aus.
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "video not found")
public class VideoNotFoundException extends RuntimeException {
}
Ihre ursprüngliche Methode kann ResponseEntity zurückgeben (ändert Ihr Methodenverhalten nicht):
@RequestMapping(value = VIDEO_DATA_PATH, method = RequestMethod.GET)
public ResponseEntity getData(@PathVariable(ID_PARAMETER) long id, HttpServletResponse res{
...
}
und geben Sie folgendes ein:
return new ResponseEntity(HttpStatus.NOT_FOUND);
Dies geschieht sehr einfach durch Auslösen von org.springframework.web.server.ResponseStatusException :
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "entity not found"
);
Es ist kompatibel mit @ResponseBody und mit jedem Rückgabewert.
Sie können responseStatus einfach wie folgt auf res setzen:
@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
...
}