@RequestParam中的Date类型的参数,如果前端给一个2001-01-01
在后端默认是不认的,我们在后端需要对这种情况进行适配,我们可以通过@ControllerAdvice注解来拦截请求,然后对Date参数进行转换,最终实现我们的需求。
public class CourseDateConverter implements Converter<String, Date> {
private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
private static final String dateFormata = "yyyy-MM-dd HH:mm:ss";
private static final String shortDateFormat = "yyyy-MM-dd";
private static final String shortDateFormata = "yyyy/MM/dd";
private static final String timeStampFormat = "^\\d+$";
@Override
public Date convert(String value) {
if (StringUtils.isEmpty(value)) {
return null;
}
value = value.trim();
try {
if (value.contains("-")) {
SimpleDateFormat formatter;
if (value.contains(":")) {
// yyyy-MM-dd HH:mm:ss 格式
formatter = new SimpleDateFormat(dateFormat);
} else {
// yyyy-MM-dd 格式
formatter = new SimpleDateFormat(shortDateFormat);
}
return formatter.parse(value);
} else if (value.matches(timeStampFormat)) {
//时间戳
Long lDate = new Long(value);
return new Date(lDate);
} else if (value.contains("/")) {
SimpleDateFormat formatter;
if (value.contains(":")) {
// yyyy/MM/dd HH:mm:ss 格式
formatter = new SimpleDateFormat(dateFormata);
} else {
// yyyy/MM/dd 格式
formatter = new SimpleDateFormat(shortDateFormata);
}
return formatter.parse(value);
}
} catch (Exception e) {
throw new RuntimeException(String.format("parser %s to Date fail", value));
}
throw new RuntimeException(String.format("parser %s to Date fail", value));
}
}
@ControllerAdvice
public class TimeControllerHandler {
@InitBinder
public void initBinder(WebDataBinder binder) {
GenericConversionService genericConversionService = (GenericConversionService) binder.getConversionService();
if (genericConversionService != null) {
genericConversionService.addConverter(new CourseDateConverter());
}
}
}
这样,前端传入的日期参数?fromDate=2001-01-01&endDate=2015-01-01,也是可以被后端成功处理的。
springboot~对@RequestParam中Date参数的适配
原文:https://www.cnblogs.com/lori/p/15217419.html