带Map的 Java Spring Boot响应实体
我有以下这段代码,它为Spring应用的响应创建一个ResponseEntity。
有没有更高效地实现这个方法?
@GetMapping("/api/payments/reservation/{idReservation}")
public ResponseEntity<Map<String, Object>> obtenerPagoReal(@PathVariable("idReservation") int idReservation) {
Payment pay = dao_interface.findByIdReserva(idReservation);
Map<String, Object> response = new HashMap<>();
if (pago!=null) {
response.put("status", "success");
response.put("code", 200);
response.put("message", "Payment done");
response.put("data", pay);
return ResponseEntity.ok(response);
} else {
response.put("status", "error");
response.put("code", 404);
response.put("message", "Payment not found");
response.put("data", null);
return ResponseEntity.status(404).body(response);
}
}
解决方案
设计API时要受系统需求的约束,但就你的代码而言,有一些建议可以用来改进实现:
- 在这个实现中存在大量冗余数据,例如当你写出类似
ResponseEntity.status(404).body(response)的代码时,已经把状态码设为404,因此你不需要再像这样定义一个response.put("code", 404);。 - 我们有不同的HTTP状态码,它们各自有明确的含义,例如404表示“未找到”,因此当你在响应中返回
404时,就不需要再有response.put("message", "Payment not found");。 - 如前所述,HTTP状态码具有不同的含义,2xx表示成功,4xx或 5xx表示错误,因此当你拥有带有404状态码的ResponseEntity时,这就意味着请求存在错误,因此你不需要再
response.put("status", "error");。 - 你可以在服务层使用DTO,以隐藏业务领域模型对象。
例如,如果我想重构你的示例代码,它将会是这样的:
@GetMapping"/api/payments/reservation/{idReservation}")
public ResponseEntity<Payment> obtenerPagoReal(@PathVariable("idReservation") int idReservation) {
Payment pay = dao_interface.findByIdReserva(idReservation);
if (pay!=null) {
return ResponseEntity.ok(pay);
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。