如果一个动作实现了“模型驱动”- modeldriven 接口,它就获得了表单数据自动传输到对象的额外能力。请参见下面的完整的例子:
一个顾客(customer)对象,有 setter 和 getter 方法。
customer.java
package com.h3.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.h3.common.action; import com.h3.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.h3.common.action.customeraction" > <result name="success">pages/addcustomer.jsp</result> </action> <action name="customeraction" class="com.h3.common.action.customeraction" > <result name="success">pages/success.jsp</result> </action> </package> </struts>
访问客户表,填写表格 (name : “h3.com”, age ” “26”) 并点击提交按钮,表单数据(name & age) 将自动转移到客户的属性(name & age) (按属性名称匹配)。
http://localhost:8080/struts2-modeldrive/addcustomeraction.action
http://localhost:8080/struts2-modeldrive/customeraction.action