SpringBoot之类型转换
类型转换就是在前端传入的和controller中接收的不一样的时候,我们需要使用相应的类型转换器来实现自动转换功能。如下:
实例
1 2 3 4 5 6 7 8
| @RestController public class HelloController { @GetMapping("/hello") public String hello(Date birth){ System.out.println(birth); return "success"; } }
|
当我们使用 localhost:8080/hello?birth=2020-01-01
访问接口的时候,会抛出错误:

大致就是:不能将String类型转为要求的Date类型。
下面我们定义一个日期类型转换器并加入到Spring容器中去:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Component public class DateConverter implements Converter<String, Date> {
@Override public Date convert(String s) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); if (s != null && !"".equals(s)){ try { return simpleDateFormat.parse(s); } catch (ParseException e) { e.printStackTrace(); } } return null; } }
|
再次访问就可以正常运行了。
Be the first guy leaving a comment!