[Spring REST] Use @RestController and @ResponseEntity

Why need to use @ResponseEntity, first let's see what problem we might have when we don't use it.

@RestController
public class ProductsRestController {

    @Autowired
    private ProductRepository productRepository;

    @GetMapping("/products")
    public List<Product> getProducts() {
        List<Product> products = new ArrayList<>();
        productRepository.findAll().forEach(p -> products.add(p));
        return products;
    }
}

If the products is not exist. When it returns

Response: {status: 200, body: {}}

which is a misleading http status code.

@GetMapping("/products")
public ResponseEntity getProductsByRequestParam(@RequestParam("name") String name) {
    List<Product> products = productRepository.searchByName(name);
    return new ResponseEntity<>(products, HttpStatus.OK);
 }

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

原文地址:https://www.cnblogs.com/Answer1215/p/14284366.html