Struts 2 ModelDriven example

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

Struts2 model driven example

http://localhost:8080/Struts2Example/customerAction.action

Struts 2 model driven example

Reference

  1. ModelDriven documentation

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
12 Comment threads
6 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
16 Comment authors
Pradeep GowdaALOK PRATAP SINGHDeepak AyarePhilippe GioseffiAndrey Recent comment authors
newest oldest most voted
Pradeep Gowda
Guest
Pradeep Gowda

i have two model class for doing one to one mapping how to use model driven to get two model class object

ALOK PRATAP SINGH
Guest
ALOK PRATAP SINGH

can you suggest me, how to use action-validation.xml in above example.

Deepak Ayare
Guest
Deepak Ayare

It was really good tutorial, but i am finding some difficulties to have a Complex Model Driven class. I have Class College and Students which has one to Many relationship, One College could have multiple students. eg: Class College { String collegeName; private Set students = new HashSet(0); //getter and setter methods } Class Student { String studentName; //getter and setter methods } //Action Class public class CollegeAction extends ActionSupport implements ModelDriven{ private College college = new College(); @Override public College getModel() { return college; } //getter and setter methods } //jsp code snippet which will be used to insert… Read more »

Philippe Gioseffi
Guest
Philippe Gioseffi

Hi,

I have a doubt about ModelDriven using complex objects that I posted in StackOverFlow.

Could you take a look and help me, please?

http://stackoverflow.com/questions/20276558/how-to-access-properties-in-the-pojo-using-struts-2-modeldriven-interface-when-y/

Andrey
Guest
Andrey

Your tutorial is great as usual – thank you a lot.

But will you please explain what do we refer in struts.xml with as ‘action name=”addCustomerAction” …’?

Lokesh Guru
Guest
Lokesh Guru

Always helpful.Can also include details of modelDriven interceptor.

Rabab
Guest
Rabab

Hi, I get this Exception org.apache.jasper.JasperException: The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. – [unknown location] Struts.xml : /vues/accueil.jsp /vues/auth_ko.jsp My action : package ma.org.projet.presentation; import java.util.List; import ma.org.projet.modele.Utilisateur; import ma.org.projet.util.HibernateUtil; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class AuthentifierUtilisateurAction extends ActionSupport implements ModelDriven { private String user; private String password; Utilisateur monUser; public String authentifier() { Session session =… Read more »

sairajesh
Guest
sairajesh

I am getting the exception like this

java.lang.NullPointerException
org.apache.struts2.impl.StrutsActionProxy.getErrorMessage(StrutsActionProxy.java:69)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:501)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:432)

rio
Guest
rio

hmm i think it cause the system can’t find ‘something’ to view,
for example, if you accessing http://localhost:8080/Struts2Example
normally it will see value in the tag in the web.xml,
if you don’t fill the value in tag, that error may occur.

try to access in full path such as the following sample.

regards

bazzinga
Guest
bazzinga

looks like its copied from roseindia with minor changes made

meet2
Guest
meet2

I got that error while running my application…..

WARNING: No configuration found for the specified action: ‘customerAction.action’ in namespace: ”. Form action defaulting to ‘action’ attribute’s literal value.
Apr 29, 2012 12:25:39 PM org.apache.struts2.components.Form evaluateExtraParamsServletRequest
WARNING: No configuration found for the specified action: ‘customerAction.action’ in namespace: ”. Form action defaulting to ‘action’ attribute’s literal value.
Apr 29, 2012 12:25:43 PM org.apache.struts2.dispatcher.Dispatcher serviceAction
SEVERE: Could not find action or result
There is no Action mapped for namespace / and action name customerAction. – [unknown location]
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:186)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:41)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:494)
at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)

shyam
Guest
shyam

Hi meet2,

Refer you url that you are typing exactly in the browser.
Verfiy whether are you specifying exact action name in the browser.

Thanks,
Shyam

George Anil John
Guest
George Anil John

Can any one explain with examples how to use struts2 validation framework that uses XML in a model driven environment.
* The condition is such that the element to be validated in the model object is inside a complex object.
Say a PIN number(pin number may be in an object called address which contain street,pin etc..)
* The model contain address,name,age as attributes.

Varun Singh
Guest
Varun Singh

Please help us understand the difference between Model driven & Preparable Interface in Struts 2 with suitable example.

Vaibhav Pawar
Guest
Vaibhav Pawar

Hello Mr. Yong, I must admit that your tutorial is really helpful. Keep the good work. :) I have a doubt regarding the above tutorial. Suppose we want to store a Foreign Key value with customer data. We, of course, can’t get it from JSP page as we got Customer information. For now, I am getting the key from a session I had created. But how to store this with your data. I am using this ModelDriven Interface. – Should I declare the foreign key variables inside my customer class? – If I declare them, how the value from session… Read more »