花开从不是为了别人的欣赏,努力也是。
一、提供出去的接口,请求入参带有时间类型参数
@GetMapping("/date")
public DateResponse get(@RequestParam(value = "localDate", defaultValue = "2020-12-12", required = false) LocalDate localDate, @RequestParam(value = "date", defaultValue = "2020-12-12 12:12:12", required = false) Date date) {
System.out.println(localDate);
System.out.println(date);
return new DateResponse();
}
当我们没有做任何配置时,请求这个接口的时候会报这样的错误:
{
"timestamp": 1592623507092,
"status": 400,
"error": "Bad Request",
"message": "Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.time.LocalDate] for value '2020-12-12'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2020-12-12]",
"path": "/date"
}
根据Failed to convert value of type ‘java.lang.String’ to required type ‘java.time.LocalDate’ 这条信息来看,程序不能将一个String类型的值转换成LocalDate类型(前端传过来的是String类型,程序会对这些数据进行相应的convert,当匹配不到类型时,就会抛ConversionFailedException异常)。那么就按照提示,补充相应的Converter就好了。
二、几种常用的Converter
PS:我们自定义的Converter需要实现org.springframework.core.convert.converter.Converter 接口,这种方式是针对全局生效的,如果只是针对某个接口,可以使用 @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) 这样的方式。
1、字符串转换成LocalDate
public class String2LocalDateConverter implements Converter<String, LocalDate> {
@Override
public LocalDate convert(String s) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return LocalDate.parse(s, fmt);
}
}
2、字符串转换成LocalDateTime
public class String2LocalDateTimeConverter implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(String s) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(s, fmt);
}
}
3、字符串转换成LocalTime
public class String2LocalTimeConverter implements Converter<String, LocalTime> {
@Override
public LocalTime convert(String s) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("HH:mm:ss");
return LocalTime.parse(s, fmt);
}
}
4、字符串转换成Date
public class String2DateConverter implements Converter<String, Date> {
@SneakyThrows
@Override
public Date convert(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.parse(s);
}
}
三、注册Converters
这里我们选择通过WebMvcConfigurationSupport 的**addFormatters(FormatterRegistry registry)**方法将自定义的Converters注册到容器里面去
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addFormatters(FormatterRegistry registry) {
registry.addConverter(new String2LocalDateConverter());
registry.addConverter(new String2LocalDateTimeConverter());
registry.addConverter(new String2LocalTimeConverter());
registry.addConverter(new String2DateConverter());
}
我们再次请求接口,就可以正确的访问了。