簡體   English   中英

rest api 得到返回 HttpStatus.NO_CONTENT

[英]rest api get return HttpStatus.NO_CONTENT

我有這個實體 class 來存儲電影細節。

@Table(name = "movie")
public class Movie {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String title;
    private String category;
    private double rating;
}

Now i also have a rest api to get by movie id How do i modify my rest api to return http error code 204, to show no content has been found.

@GetMapping("/movie/{id}")
public Movie getMovieById(@PathVariable(value = "id") Integer id) {
    if (service.get(id)!=null) {
        return service.get(id);
    } else {
        return HttpStatus.NO_CONTENT;
    }
}

204 No Content 不是這里合適的狀態碼; 這意味着“資源存在/存在,但我沒有發送內容”。 404 Not Found 尤其如此。 您可以拋出異常(例如ResponseStatusException )或更改 controller 以返回ResponseEntity<Movie>

如果要求的內容不可用,您可以堅持 404 Resource Not found。 使用其他一些晦澀的(不是 204)HTTP 狀態代碼不是一個好主意,因為它可能導致瀏覽器做出不同的反應。 在您的情況下,返回任何空的響應主體也可以。

you can do something like below,

@Table(name = "movie")
public class Movie {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String title;
    private String category;
    private double rating;
    public String status;
}

@GetMapping("/movie/{id}")
public ResponseEntity<Movie> getMovieById(@PathVariable(value = "id") Integer id) {

ResponseEntity<Movie> response = null;

    if (service.get(id)!=null) {
        Movie movie =  service.get(id);
        ResponseEntity.ok(movie)
    } else {
        Movie movie = new Movie()
        movie.setStatus("FAILURE");
        ResponseEntity response = new ResponseEntity<>(movie, HttpStatus.NOT_FOUND)
    }
    
    return response
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM