struts2中的ModelDriven使用


例子都為struts2中的文檔例子

JSP提交數據:

<s:form action="modelDrivenResult" method="POST" namespace="/modelDriven">   
    <s:textfield label="Gangster Name" name="name" />
    <s:textfield label="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>

 根據數據提交的action,和namespace,修改struts.xml的內容

添加下面配置到struts.xml

    <package name="base2" namespace="/modelDriven" extends="struts-default">
        <action name="modelDrivenResult" class="ModelDrivenAction">
            <result>/Hello.jsp</result>
        </action>
    </package>

 然后添加處理數據的action,這里使用ModelDriven的方式。該action繼承ModelDriven接口,實現getModel()方法,方法只返回一個模型對象,默認轉換Object。只要改模型對象提供的方法和提交數據的name屬性對應,struts2就能自動把數據賦給模型對象,最后對象提供各種get方法把數據存放在值棧,傳遞到Hello.jsp。

處理的action,返回模型對象Gangster。

public class ModelDrivenAction extends ActionSupport implements ModelDriven { 
    public String execute() throws Exception {
        return SUCCESS;
    }

    public Object getModel() {
        return new Gangster();
    }
}

 

模型類

public class Gangster implements Serializable {
    private String name;
    private int age;
    private String description;
    private boolean bustedBefore;

    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public boolean isBustedBefore() {
        return bustedBefore;
    }
    public void setBustedBefore(boolean bustedBefore) {
        this.bustedBefore = bustedBefore;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

 最后Hello.jsp中可以使用<s:property value=".."/>取值,value直接使用相應的age,name等。而action雖然提供的getModel()方法,但因為轉為了Object,而Object不能提供取值的方法,所以無法使用value="model.xxx"來取值。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM