Struts2模型驅動實例
這裡我們創建一個web工程為:struts2-modeldrive ,用於講解演示Struts2模型驅動這一章內容的學習。
如果一個動作實現了“模型驅動”- ModelDriven 接口,它就獲得了表單數據自動傳輸到對象的額外能力。請參見下麵的完整的例子:
1. 域對象
一個顧客(customer)對象,有 setter 和 getter 方法。
Customer.java
package com.gitbook.netmon; 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; } }
2. 動作 - Action
Action類,實現了模型驅動ModelDriven 接口,聲明getModel()方法返回客戶的對象。當表單數據提交到這個動作,它會自動將表單數據傳輸到客戶的屬性。
客戶對象必須手動初始化。
CustomerAction.java
package com.gitbook.netmon.action; import com.gitbook.netmon.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; } }
3. JSP頁麵
JSP頁麵的模型驅動(ModelDriven)的示範。
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>
4. struts.xml
<?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.gitbook.netmon.action.CustomerAction" > <result name="success">pages/addCustomer.jsp</result> </action> <action name="customerAction" class="com.gitbook.netmon.action.CustomerAction" > <result name="success">pages/success.jsp</result> </action> </package> </struts>
5. 示例
訪問客戶表,填寫表格 (name : “gitbook.net”, age ” “26”) 並點擊提交按鈕,表單數據(name & age) 將自動轉移到客戶的屬性(name & age) (按屬性名稱匹配)。
http://localhost:8080/struts2-modeldrive/addCustomerAction.action
http://localhost:8080/struts2-modeldrive/customerAction.action
工程源代碼下載 - http://pan.baidu.com/s/1hqxyjf2