Dav*_*idR 11 java spring spring-mvc
我的Spring应用程序中有一个REST端点,如下所示
@RequestMapping(value="/customer/device/startDate/{startDate}/endDate/{endDate}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public Page<DeviceInfo> getDeviceListForCustomerBetweenDates(@PathVariable ZonedDateTime startDate, @PathVariable ZonedDateTime endDate, Pageable pageable) {
... code here ...
}
Run Code Online (Sandbox Code Playgroud)
我试过传递路径变量作为毫秒和秒.但是,我从两个方面得到以下异常:
"Failed to convert value of type 'java.lang.String' to required type 'java.time.ZonedDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.web.bind.annotation.PathVariable java.time.ZonedDateTime for value '1446361200'; nested exception is java.time.format.DateTimeParseException: Text '1446361200' could not be parsed at index 10"
Run Code Online (Sandbox Code Playgroud)
有人可以解释我如何传入(如秒或毫秒)字符串,如1446361200,并让它转换为ZonedDateTime?
或者是作为String传递然后自己进行转换的唯一方法?如果是这样,有一种通用的方法来处理具有类似设计的多种方法吗?
Sot*_*lis 12
有一个默认的ZonedDateTime参数转换器.它使用Java 8 DateTimeFormatter创建的
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
Run Code Online (Sandbox Code Playgroud)
就你而言,这可能是任何FormatStyle或任何真正的DateTimeFormatter,你的例子不会有效.DateTimeFormatter解析和格式化日期字符串,而不是时间戳,这是您提供的.
您可以@org.springframework.format.annotation.DateTimeFormat为参数提供适当的自定义,例如
public Page<DeviceInfo> getDeviceListForCustomerBetweenDates(
@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime startDate,
@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime endDate,
Pageable pageable) { ...
Run Code Online (Sandbox Code Playgroud)
或者使用适当的pattern和相应的日期字符串
2000-10-31T01:30:00.000-05:00
您将无法使用unix时间戳执行上述任何操作.在适当的情况下,ZonedDateTime通过时间戳进行转换的规范方法是通过.Instant#ofEpochSecond(long)ZoneId
long startTime = 1446361200L;
ZonedDateTime start = Instant.ofEpochSecond(startTime).atZone(ZoneId.systemDefault());
System.out.println(start);
Run Code Online (Sandbox Code Playgroud)
要使其工作@PathVariable,请注册自定义Converter.就像是
class ZonedDateTimeConverter implements Converter<String, ZonedDateTime> {
private final ZoneId zoneId;
public ZonedDateTimeConverter(ZoneId zoneId) {
this.zoneId = zoneId;
}
@Override
public ZonedDateTime convert(String source) {
long startTime = Long.parseLong(source);
return Instant.ofEpochSecond(startTime).atZone(zoneId);
}
}
Run Code Online (Sandbox Code Playgroud)
并将其注册在带注释的类中,覆盖WebMvcConfigurationSupport @ConfigurationaddFormatters
@Override
protected void addFormatters(FormatterRegistry registry) {
registry.addConverter(new ZonedDateTimeConverter(ZoneId.systemDefault()));
}
Run Code Online (Sandbox Code Playgroud)
现在,Spring MVC将使用此转换器将String路径段反序列化为ZonedDateTime对象.
在Spring Boot中,我认为你可以@Bean为相应的声明一个Converter,它会自动注册它,但是不要接受我的话.
你会需要接受你传递什么@PathVariable作为String数据类型,然后自己做转换,您的错误日志很明确地告诉你.
不幸的是,Spring库无法将String值"1446361200"转换ZonedDateTime为通过@PathVariable绑定类型.
| 归档时间: |
|
| 查看次数: |
8415 次 |
| 最近记录: |