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

时间:2014-08-21 09:02:53

标签: java spring http-status-code-404 retrofit

我使用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());
  新的ResponseEntity(HttpStatus.BAD_REQUEST);

但我需要返回Response

如果视频为空,如何在此处返回404状态代码?

4 个答案:

答案 0 :(得分:50)

使用NotFoundException注释创建一个@ResponseStatus(HttpStatus.NOT_FOUND)类,并将其从控制器中抛出。

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

答案 1 :(得分:23)

您的原始方法可以返回 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);

答案 2 :(得分:9)

这很简单,只需抛出 org.springframework.web.server.ResponseStatusException

let myImage = UIImageView(frame: outerView.bounds)
myImage.clipsToBounds = true
myImage.layer.cornerRadius = 10

它与@ResponseBody和任何返回值兼容。需要Spring 5 +

答案 3 :(得分:1)

您可以在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
 ...
}