阅读完需:约 1 分钟
类型转换主要用在日期上,前端传来一个日期,后端如何来接收呢?
例子目录:

先写一个UserController
文件 ,运行访问
@RestController
public class UserController {
@GetMapping("/hello")
public void hello(Date birth){
System.out.println(birth);
}
}
结果会报错:

虽然后台没有报错但是会给警告
2020-03-18 01:14:58.957 WARN 22916 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2000-01-01'; nested exception is java.lang.IllegalArgumentException]
这个时候我们就要加一个类型转换器来转换日期了
@Component
public class DateConverter implements Converter<String, Date> {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date convert(String s) {
if(s!=null && !"".equals(s)){
try {
return sdf.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
用来转换日期的类
测试结果:

