Skip to content

Instantly share code, notes, and snippets.

@yanhua365
Last active December 31, 2015 00:28
Show Gist options
  • Save yanhua365/7907207 to your computer and use it in GitHub Desktop.
Save yanhua365/7907207 to your computer and use it in GitHub Desktop.
在Spring MVC的Controller里注册一个转换领域对象的PropertyEditor。
@InitBinder
public void initBinder(WebDataBinder binder) {
//下面是自定义一个日期转换的PropertyEditor
//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//dateFormat.setLenient(false);
//binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
//定义UpdateTemplate转换的PropertyEditor
binder.registerCustomEditor(UpdateTemplate.class, new PropertyEditorSupport() {
@Override
public String getAsText() {
if(getValue() == null){
return "";
}
return ((UpdateTemplate)getValue()).getId()+"";
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if(Strings.isNullOrEmpty(text)){
setValue(null);
return;
}
Long id = Long.valueOf(text);
setValue(updateTemplateService.find(id));
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment