我正在寻找在Spring MVC中绑定和转换数据的最简单和最简单的方法.如果可能,不进行任何xml配置.
到目前为止,我一直在使用PropertyEditors:
public class CategoryEditor extends PropertyEditorSupport {
// Converts a String to a Category (when submitting form)
@Override
public void setAsText(String text) {
Category c = new Category(text);
this.setValue(c);
}
// Converts a Category to a String (when displaying form)
@Override
public String getAsText() {
Category c = (Category) this.getValue();
return c.getName();
}
}
Run Code Online (Sandbox Code Playgroud)
和
...
public class MyController {
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Category.class, new CategoryEditor());
}
...
}
Run Code Online (Sandbox Code Playgroud)
它很简单:两个转换都在同一个类中定义,绑定很简单.如果我想在我的所有控制器上进行通用绑定,我仍然可以在我的xml配置中添加3行 …