You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot GET请求日期参数转换失败问题求助

问题描述

我定义了如下Flight实体类:

@Entity
@Data
@Table(name = "flights")
@NoArgsConstructor
@AllArgsConstructor
public class Flight{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long flightId;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="departure_from", referencedColumnName="location")
    private Airport departureFrom;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="arrival_to", referencedColumnName="location")
    private Airport arrivalTo;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", shape = Shape.STRING)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "departure_date", columnDefinition = "DATETIME")
    private Date departureDate;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", shape = Shape.STRING)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "return_date", columnDefinition = "DATETIME")
    private Date returnDate;
    private Long flightPrice;
}

POST请求可成功创建实例,但使用包含departureFrom、arrivalTo、departureDate和returnDate参数的GET请求查询时,出现错误:

Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'.

我的GET接口代码如下:

@GetMapping("/flights/search/id")
public ResponseEntity<?> searchFlightsById(@RequestParam("departure_from") Airport departureFrom, @RequestParam("arrival_at") Airport arrivalAt, @RequestParam("departure_date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date departureDate, @RequestParam("return_date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Optional<Date> returnDate){
    return ResponseEntity.ok(flightService.fetchFlights(departureFrom, arrivalAt, departureDate, returnDate));
}

不带日期参数的GET请求返回的日期格式为YYYY:MM:dd HH:mm:ss,与MySQL中的格式一致。我是SpringBoot和Java新手,希望得到解决该问题的建议。

解决建议

1. 严格匹配请求日期格式

确保GET请求中departure_date和return_date参数的格式严格遵循yyyy-MM-dd HH:mm:ss,比如2024-05-20 14:30:00,不要出现格式错误(比如用/分隔日期、缺少时分秒、多余符号等)。

2. 替换为Java 8+日期类型(推荐)

java.util.Date是旧API,Spring对java.time.LocalDateTime等新日期类型的支持更稳定,建议替换:

  • 修改实体类日期字段:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", shape = Shape.STRING)
@Column(name = "departure_date", columnDefinition = "DATETIME")
private LocalDateTime departureDate;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", shape = Shape.STRING)
@Column(name = "return_date", columnDefinition = "DATETIME")
private LocalDateTime returnDate;
  • 修改接口参数(注意给可选参数加上required = false):
@RequestParam("departure_date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime departureDate,
@RequestParam(value = "return_date", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Optional<LocalDateTime> returnDate

3. 全局配置日期转换器

可以在配置类中全局定义日期格式,避免每个参数都加注解:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 针对LocalDateTime的全局配置
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        registry.addFormatterForFieldType(LocalDateTime.class, new DateTimeFormatterFormatter(dateTimeFormatter));
        
        // 如果继续使用Date,添加此配置
        registry.addFormatterForFieldType(Date.class, new DateFormatter("yyyy-MM-dd HH:mm:ss"));
    }
}

4. 修复Airport参数的转换问题

接口直接接收Airport类型参数会导致转换错误,Spring无法自动将字符串转为Airport对象,有两种解决方式:

  • 改为接收字符串参数,在方法内查询实体:
@RequestParam("departure_from") String departureLocation
// 方法内:
Airport departureFrom = airportRepository.findByLocation(departureLocation)
        .orElseThrow(() -> new IllegalArgumentException("无效的出发机场"));
  • 自定义转换器让Spring自动转换:
@Component
public class StringToAirportConverter implements Converter<String, Airport> {
    private final AirportRepository airportRepository;

    public StringToAirportConverter(AirportRepository airportRepository) {
        this.airportRepository = airportRepository;
    }

    @Override
    public Airport convert(String location) {
        return airportRepository.findByLocation(location)
                .orElseThrow(() -> new IllegalArgumentException("无效的机场位置: " + location));
    }
}

内容的提问来源于stack exchange,提问作者beneficarum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 15:26:09