Spring Boot接口返回200 OK但responseData为空排障求助
Spring Boot接口返回200但responseData为空的问题排查与修复
问题现象
发送GET请求到/find-flights/BOM/DEL/2024-06-17时,接口返回200 OK状态,但响应体中responseData数组为空[{}],未获取到预期的MySQL数据库航班数据。
核心问题定位
Controller的findFlights方法已接收departureDate路径参数,但实际调用Service时,使用的是flightService.findFlightsByAirport(originAirport, destinationAirport)——完全忽略了日期参数,导致查询仅按起飞机场和目的地机场筛选,未加入日期条件。若数据库中仅存在日期不匹配的航班,或无符合机场条件的航班数据,就会返回空列表,最终序列化出[{}]的响应结果。
修复步骤
- 修改Controller层,调用支持日期查询的Service方法
将原代码中调用Service的语句替换为带日期参数的方法:
List<Flight> flights = flightService.findFlightsByDate(originAirport, destinationAirport, departureDate);
- 优化日志输出(可选)
添加日期参数到日志中,方便后续排查:
System.out.println("Searching flights with origin: " + originAirport + ", destination: " + destinationAirport + ", departure date: " + departureDate);
额外优化建议
- 日期类型匹配检查:确认Flight实体类中
departureDate字段的类型(如LocalDate/Date),确保请求参数2024-06-17能正确转换为对应类型;若Repository方法参数为String,需保证数据库存储的日期字符串格式与请求参数完全一致,避免格式不匹配导致查询失效。 - 空列表响应处理:当前代码中,当航班列表为空时未设置
responseData,导致响应体出现[{}]。建议在空列表场景下也执行resp.setResponseData(flights);,使响应返回标准空数组[],更符合前端预期。 - 异常状态码调整:捕获异常时返回
HttpStatus.BAD_REQUEST不准确,建议改为HttpStatus.INTERNAL_SERVER_ERROR,更贴合HTTP状态码的语义规范。
修改后的Controller代码示例
@RestController public class AppController { @Autowired private FlightService flightService; @GetMapping("/find-flights/{originAirport}/{destinationAirport}/{departureDate}") public ResponseEntity<ObjectResponse> findFlights(@PathVariable String originAirport, @PathVariable String destinationAirport, @PathVariable String departureDate) { System.out.println("Searching flights with origin: " + originAirport + ", destination: " + destinationAirport + ", departure date: " + departureDate); ObjectResponse resp = new ObjectResponse(); try{ List<Flight> flights = flightService.findFlightsByDate(originAirport, destinationAirport, departureDate); if (flights.isEmpty()) { resp.setResponseData(flights); resp.setMessage("No Flights Found"); resp.setMessageType("error"); resp.setStatusCode(HttpStatus.OK); } else { resp.setResponseData(flights); resp.setStatusCode(HttpStatus.OK); resp.setMessage("Flights Found"); resp.setMessageType("success"); } }catch (Exception ex){ resp.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); resp.setMessage("Error occurred on the server"); resp.setMessageType("error"); ex.printStackTrace(); } return new ResponseEntity<>(resp, resp.getStatusCode()); } }
内容的提问来源于stack exchange,提问作者Smit Patel
相关产品推荐
相关产品推荐

