If an Action implements the “ModelDriven
” interface, it gains the extra ability to transfer the form data into the object automatically. See a complete example below :
1. Domain object
A customer object, with setter and getter methods.
Customer.java
package com.mkyong.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;
}
}
2. Action
Action class, implements the ModelDriven
interface, declared the getModel()
method to return the customer
’s object. When the form data is submitted to this action, it will transfers the form data into the customer properties automatically.
The customer object have to be initialize manually.
CustomerAction.java
package com.mkyong.common.action;
import com.mkyong.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;
}
}
3. JSP page
JSP pages for the ModelDriven
demonstration.
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
Link it all ~
<?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.mkyong.common.action.CustomerAction" >
<result name="success">pages/addCustomer.jsp</result>
</action>
<action name="customerAction"
class="com.mkyong.common.action.CustomerAction" >
<result name="success">pages/success.jsp</result>
</action>
</package>
</struts>
5. Demo
Access the customer form, fill in the form (name : “mkyong”, age ” “123456”) and hits the submit button, the form data (name & age) will be transferred into the customer’s properties (name & age) (match by property name) automatically.
http://localhost:8080/Struts2Example/addCustomerAction.action