Spring项目查询不到产品对象时如何返回404状态码
实现方案
你可以通过在控制器层判断产品集合是否为空,抛出404状态异常来实现需求,Spring 5及以上版本推荐使用ResponseStatusException直接返回指定HTTP状态码,具体修改如下:
第一步:导入必要依赖类
在UiController的导入部分新增以下类:
import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException;
第二步:修改控制器方法逻辑
对三个查询产品的接口都增加空判断,无数据时直接抛出404异常:
@Controller public class UiController { private ProductService productService; private LocationService locationService; private InventoryService inventoryService; private CartService cartService; public UiController( ProductService productService, LocationService locationService, InventoryService inventoryService, CartService cartService) { this.productService = productService; this.locationService = locationService; this.inventoryService = inventoryService; this.cartService = cartService; } @GetMapping("/") public String home(Model model) { List<Product> products = productService.getAllProducts(); // 空校验,无数据抛出404 if (products == null || products.isEmpty()) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "未查询到产品数据"); } model.addAttribute("products", products); return "index"; } @GetMapping("/brand/{brand}") public String brand(Model model, @PathVariable String brand) { List<Product> products = productService.getProductByBrand(brand); if (products == null || products.isEmpty()) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "该品牌下无对应产品"); } model.addAttribute("products", products); return "index"; } @GetMapping("/product/{productId}") public String product(Model model, @PathVariable String productId) { Product prod = productService.getProduct(productId); // 先判断查询的单个产品是否为空 if (prod == null) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "该产品不存在"); } ArrayList<Product> ps = new ArrayList<Product>(); ps.add(prod); model.addAttribute("products", ps); return "index"; } }
第三步:自定义404页面(可选)
如果你需要自定义404的展示样式,只需在项目的src/main/resources/templates目录下新建404.html文件,编写你需要的404页面内容即可,Spring Boot默认会自动将404状态请求映射到该模板页面。
注意事项
- 建议
ProductService层的方法无数据时统一返回空集合而非null,可以减少空指针判断的冗余代码 - 原单产品查询接口的逻辑如果查询结果为
null,会生成size为1但元素为null的集合,渲染页面时会报错,所以必须优先判断产品对象是否为空
内容的提问来源于stack exchange,提问作者Igor Shmukler
相关产品推荐
相关产品推荐

