如果一個動作實現(xiàn)了“模型驅(qū)動”- ModelDriven 接口,它就獲得了表單數(shù)據(jù)自動傳輸?shù)綄ο蟮念~外能力。請參見下面的完整的例子:
一個顧客(customer)對象,有 setter 和 getter 方法。
Customer.java
package com.yiibai.common; public class Customer{ String name; int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Action類,實現(xiàn)了模型驅(qū)動ModelDriven 接口,聲明getModel()方法返回客戶的對象。當(dāng)表單數(shù)據(jù)提交到這個動作,它會自動將表單數(shù)據(jù)傳輸?shù)娇蛻舻膶傩浴?
CustomerAction.java
package com.yiibai.common.action; import com.yiibai.common.Customer; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class CustomerAction extends ActionSupport implements ModelDriven{ //have to initialize it Customer customer = new Customer(); public String execute() throws Exception { return SUCCESS; } public Object getModel() { return customer; } }
addCustomer.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> </head> <body> <h1>Struts 2 ModelDriven example</h1> <h2>Add Customer</h2> <s:form action="customerAction" > <s:textfield name="name" label="Name" /> <s:textfield name="age" label="Age" value=""/> <s:submit /> </s:form> </body> </html>
success.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> </head> <body> <h1>Struts 2 ModelDriven example</h1> <h2>Customer Details</h2> Name : <s:property value="name" /><br> Age : <s:property value="age" /><br> </body> </html>
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="addCustomerAction" class="com.yiibai.common.action.CustomerAction" > <result name="success">pages/addCustomer.jsp</result> </action> <action name="customerAction" class="com.yiibai.common.action.CustomerAction" > <result name="success">pages/success.jsp</result> </action> </package> </struts>
訪問客戶表,填寫表格 (name : “yiibai.com”, age ” “26”) 并點擊提交按鈕,表單數(shù)據(jù)(name & age) 將自動轉(zhuǎn)移到客戶的屬性(name & age) (按屬性名稱匹配)。
http://localhost:8080/struts2-modeldrive/addCustomerAction.action
http://localhost:8080/struts2-modeldrive/customerAction.action