如果一個動作實現了「模型驅動」- ModelDriven 介面,它就獲得了表單資料自動傳輸到物件的額外能力。請參見下面的完整的例子:
一個顧客(customer)物件,有 setter 和 getter 方法。
Customer.java
package com.tw511.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類,實現了模型驅動ModelDriven 介面,宣告getModel()方法返回客戶的物件。當表單資料提交到這個動作,它會自動將表單資料傳輸到客戶的屬性。
CustomerAction.java
package com.tw511.common.action; import com.tw511.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.tw511.common.action.CustomerAction" > <result name="success">pages/addCustomer.jsp</result> </action> <action name="customerAction" class="com.tw511.common.action.CustomerAction" > <result name="success">pages/success.jsp</result> </action> </package> </struts>
存取客戶表,填寫表格 (name : 「tw511.com」, age 」 「26」) 並點選提交按鈕,表單資料(name & age) 將自動轉移到客戶的屬性(name & age) (按屬性名稱匹配)。
http://localhost:8080/struts2-modeldrive/addCustomerAction.action
http://localhost:8080/struts2-modeldrive/customerAction.action