相关疑难解决方法(0)

Spring MVC类型转换:PropertyEditor还是Converter?

我正在寻找在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行 …

java data-binding spring spring-mvc type-conversion

129
推荐指数
3
解决办法
5万
查看次数

标签 统计

data-binding ×1

java ×1

spring ×1

spring-mvc ×1

type-conversion ×1