背景:controller接收参数,进行处理,比如时间类型
目录
一、@ControllerAdvice使用
此注解,针对controller层有效,会在接收参数之前进行处理,WebDataBinder为接收的参数内容,再次进行处理,建议放在web.common中,无需spi
二、参考代码
@ControllerAdvice
public class ControllerInitBinderHandler {
/**
* 用于 controller 类型转换
* @param binder
*/
@InitBinder
protected void initBinder(WebDataBinder binder) {
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")));
}
});
}
}