通過一個前端和後端日期的類型轉換,來說明 SpringBoot 的類型轉換器的使用
文章目錄
一、問題引入
@Controller
public class HelloController {
@GetMapping("/hello")
public void getHello(Date birth){
System.out.println(birth);
}
}
通過前端傳入日期參數,發現報錯:
可以發現,是類型轉換錯誤
二、自定義類型轉換器
@Component
//這裏的String是源類型,Date 是要轉換的類型
public class DateConverter implements Converter<String, Date> {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date convert(String source) {
if (source != null && !"".equals(source)) {
try {
return sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}