SpringFramework使用类型参数自定义绑定

时间:2014-11-19 08:10:17

标签: java spring spring-mvc

我想将自定义对象/接口实现绑定到我的控制器。

class Form{
    private Action action;
    // setter/getter
}

interface Action{}

class Action1 implements Action{}

class Action2 implements Action{}


@Controller
class ActionController{
    @RequestMapping("/")
    public String action(Form form){
      form.getAction(); // this should be an instance of Action1 or Action2
    }
}

要确定它是Action1还是Action2,我想在HTML表单中添加一个类型参数。

<input name="form.action.type" value="1" />

是否有类似的东西已经可用,或者有人知道如何实现这一点。

我已经看过PropertyEditors,但据我所知,你只能得到一个字段作为字符串,而且似乎你无法访问任何其他属性。 如果可能的话,我正在寻找一种比创建自己的HandlerMethodArgumentResolver更简单的方法

1 个答案:

答案 0 :(得分:1)

你无法完全这样做。当控制器声明ModelAttribute参数时,Spring首先创建一个空对象并设置其参数或其子对象的参数。因此,在分析form.action.type参数之前,必须先创建一个Action对象。

一种方法是使用默认的Action实现,它将能够直接接受所有表单参数。然后getter将生成正确的Action类型。

private class ActionDefault {
    // parameters and setters to store all form fields at appropriate level
}

class Form {
    Action action = null;
    ActionDefault actionDefault = new ActionDefault();

    Action getAction() {
        if (action == null) {
            // generates proper Action object and affects it to action
        }
        return action;
    }
    // getter and setter for actionDefault;
}