How Struts2 ModelDriven interface works

2020-02-05 09:05发布

I have a doubt. How the Struts2 Modeldriven interface works. In my application I used for a single form. And I placed setters and getters as same as form names. Is it possible to place multiple ModelDriven objects with setter and getter. If I placed like that then how it will recognize?

3条回答
冷血范
2楼-- · 2020-02-05 09:27

In case of ModelDriven, you can populate only one pojo at a time. You can not use multiple ModelDriven in single action class. Because getModel() method populate the Object of the Pojo which is specified in ModelDrive<Pojo>.It will try to find the getter in this pojo. The name of the field should be matched with the form names.

查看更多
狗以群分
3楼-- · 2020-02-05 09:38

Any action implementing the ModelDriven interface must supply a getModel() method which returns the object that represents the action's model. Any parameters passed to the action are assumed to be sub-properties of the model. You may only have one model per action in a ModelDriven action.

For example, lets assume we have a model called Profile and an action to edit our profile. In our form, we have a text field for our website. Without using ModelDriven, you would have getWebsite and setWebsite methods on your action. With ModelDriven, the getter and setter on the model would be called instead. Effectively, getModel().setWebsite("http://stackoverflow.com").

Example

public class EditProfileAction extends ActionSupport implements ModelDriven<Profile> {
    private Profile profile;

    // todo: other methods

    @Override
    public Profile getModel() {
        return profile;
    }
}

public class Profile {
    private String website;

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }
}
查看更多
我想做一个坏孩纸
4楼-- · 2020-02-05 09:52

Agree... ModelDriven looks similar to ActionForm in Struts1 and to have the similarity i believe this approach is provided. Even then if u have your model, with many composition u would have to follow the ObjectBacked approach to set the contained object values in the model.

查看更多
登录 后发表回答