一般不添加任何配置的情况下,后台接收Date类型的字段会出现如下异常:
Failed to convert from type [java.lang.String] to type [java.util.Date] for value
常见解决方案可以在接收实体类的Date参数上添加注解
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime date;
然而如果在每个生成的实体类中,给每一个带有Date类型接收的参数上添加如上注解,感觉又不太节能。
因此我们自定义一个日期参数转换器让他自动转换,分为俩步。
第一步
import org.springframework.core.convert.converter.Converter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 日期转换类
* 将标准日期、标准日期时间、时间戳转换成Date类型
* @author godissleepy
*/
public class DateConverter implements Converter<String,Date> {
private final SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public Date convert(String s) {
if ("".equals(s) || null == s) {
return null;
}
try {
return smf.parse(s);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
第二步
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
}
}
写个简单的接口测试一下
@GetMapping("/getDate")
public Date getDate(Date date) {
return date;
}