首先Java 8的日期类型LocalDate,LocalDateTime,LocalTime在Mybatis中并没有映射关系,为此mybatis推出了一个补丁。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-typehandlers-jsr310</artifactId>
<version>1.0.1</version>
</dependency>
在Controller的方法参数里,如果使用了
@RequestParam("date") LocalDate date
当我们传递参数时,会被当成字符串,抛出异常。需要添加一个Controller增强器
@ControllerAdvice
public class GlobalJava8DateHandler {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class,new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(DateUtils.parse(text,DateUtils.pattern4));
}
});
binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
});
binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
});
binder.registerCustomEditor(LocalTime.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(LocalTime.parse(text, DateTimeFormatter.ofPattern("HH:mm:ss")));
}
});
}
}
@InitBinder,用于request中自定义参数解析方式进行注册,从而达到自定义指定格式参数的目的。