一、问题

如果前端传来一个日期参数,是用 String 类型的,我们如何在后端进行传参呢?

也即如下这种情况:

1
2
3
4
5
6
7
8
@RestController
public class HelloController {

@GetMapping("/hello")
public void hello(Date date) {
System.out.println(date);
}
}

浏览器输入:http://localhost:8080/hello?date=2020-01-01

可以在后台看到 WARN

Failed to convert value of type ‘java.lang.String’ to required type ‘java.util.Date’

二、解决

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Component
public class StringTransDate implements Converter<String, Date> {

private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

@Override
public Date convert(String s) {
if (s != null && !"".equals(s)) {
try {
return simpleDateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}

注:要将该类使用 @Component 注入

评论