Model Driven

来源:互联网 发布:ps4网络nat类型失败 编辑:程序博客网 时间:2024/05/23 01:35

Struts 2 does not have "forms" like Struts 1 did. In Struts 2 request parameters are bound directly to fields in the actions class, and this class is placed on top of the stack when the action is executed.

If an action class implements the interface com.opensymphony.xwork2.ModelDriven then it needs to return an object from the getModel() method. Struts will then populate the fields of this object with the request parameters, and this object will be placed on top of the stack once the action is executed. Validation will also be performed on this model object, instead of the action.

Interceptor

To use ModelDriven actions, make sure that the Model Driven Interceptor is applied to your action. This interceptor is part of the default interceptor stack defaultStack so it is applied to all actions by default.

Example

Action class:

publicclass ModelDrivenAction implementsModelDriven {
    publicString execute() throwsException {
        returnSUCCESS;
    }
 
    publicObject getModel() {
        returnnew Gangster();
    }
}

Gangster class (model):

publicclass Gangster implementsSerializable {
    privateString name;
    privateint age;
    privateString description;
    privateboolean bustedBefore;
 
    publicint getAge() {
        returnage;
    }
    publicvoid setAge(intage) {
        this.age = age;
    }
    publicboolean isBustedBefore() {
        returnbustedBefore;
    }
    publicvoid setBustedBefore(booleanbustedBefore) {
        this.bustedBefore = bustedBefore;
    }
    publicString getDescription() {
        returndescription;
    }
    publicvoid setDescription(String description) {
        this.description = description;
    }
    publicString getName() {
        returnname;
    }
    publicvoid setName(String name) {
        this.name = name;
    }
}

JSP for creating a Gangster:

<s:formaction="modelDrivenResult" method="POST" namespace="/modelDriven">  
    <s:textfieldlabel="Gangster Name" name="name" />
    <s:textfieldlabel="Gangster Age"  name="age" />
    <s:checkbox label="Gangster Busted Before" name="bustedBefore" />
    <s:textarea cols="30" rows="5" label="Gangster Description" name="description" />          
    <s:submit/>
</s:form>

Generated by CXF SiteExporter


摘自  http://struts.apache.org/release/2.3.x/docs/model-driven.html

0 0
原创粉丝点击