Davinder has posted 2 posts at DZone. View Full User Profile

Ext JS Forms Integration with Struts2

03.16.2013
| 7380 views |
  • submit to reddit

This article provides the steps to integrate a form created using Ext JS with Struts2
back-end.

A little about Ext JS

Ext JS is a cross-browser JavaScript library for building rich internet applications. Ext JS is available under commercial as well as open source license.

1.  Ext JS provides a whole lot of built-in GUI components. These components come in handy while developing a new application from scratch. There is always a component available for almost all kind of RIA GUI.

2.  Ext JS follows component design model. One can easily extend any of the core components to meet their specific requirements.

3.  Whether it’s IE or latest chrome browser, Ext JS applications look and behave the same no matter where they run. Ext JS utilizes HTML5 features on modern browsers and falls back to alternatives on older browsers.

4.  Ext JS uses AJAX to interact with web server. This enhances the RIA experience. 

Integrating Ext JS with Struts 2

Ext JS forms are submitted using AJAX by default and it expects a JSON/XML response from the server. The response must have a ‘success’ property which determines whether errors are returned from server or not. In case of error response the ‘errors’ property of response is used to set the error messages. We will discuss more in this in later section.

Struts 2 can handle the request from Ext JS like any other request and no special arrangements are needed for that. But to generate json response we need to use json plugin. The procedure to use this json plugin is mentioned in later section.

Now we have got the basic idea about Ext JS and struts 2 integration, let us create a sample example to see how it works.

Ext JS Form

First create a simple form in Ext JS. For simplicity we have created a form with 3 fields and a submit button. The form field labels are First Name, Last Name and Age.

Ext JS uses form field names as parameter names while submitting the request to server. Hence we need to provide the names for each field whose value we want to send to the server.

{
    xtype: 'textfield',
    padding: 10,
    width: 303,
    name: 'firstName',
    fieldLabel: 'First Name'
},
{
    xtype: 'textfield',
    padding: 10,
    width: 302,
    name: 'lastName',
    fieldLabel: 'Last Name'
},
{
    xtype: 'numberfield',
    padding: 10,
    width: 186,
    name: 'age',
    fieldLabel: 'Age'
}

To enable struts action to read the form data correctly, we need to make sure we have the attributes in the action class with same names as the names mentioned above in Ext JS form. We should also define the action attributes with correct data types to allow auto conversion by struts. One important point to keep in mind is that we should have public get/set method for each of the attribute defined to capture submitted form field data. Please check the form action code in below section for more details on this.

Submit button handler

When submit button is clicked, the JS function associated with the button handler would be invoked. This function sets the form URL and invoke submit() method of the form defined in Ext JS. The simplest form of button handler could be as shown below:

var form = button.up('form').getForm();
form.url='registerUser';
//form.submit();

form.submit({
    success: function(form, action) {
        Ext.Msg.alert('Success', 'The form is submitted successfully.');
    },
    
    failure: function(form, action) {
        Ext.Msg.alert('Failed', 'There is some error returned from the server.');
    }
});

There are two ways in which a form can be submitted using Ext JS’s form. If we do not want to process the response from server after submitting the form then we can simply call ‘submit()’ method without any arguments. This way is commented in above code sample.

Ext JS provides a way to process the response after submit. The ‘submit()’  method can have two callback methods configure – success and failure.

success is invoked when the response has success property set to true.

failure is invoked if the success property is missing in response or it is set to false.

Struts 2 Action

Now we have looked into the client side of code. Let us now focus on the server side of code for handling the submitted form data. The below code provides the details of our action class.

public class Registration {

	private boolean success;
	private String firstName;
	private String lastName;
	private int age;
	
	public String registerUser() {
		
		System.out.println("Got following user details: " );
		System.out.println("First Name: " + getFirstName());
		System.out.println("Last Name: " + getLastName());
		System.out.println("Age: " + getAge());
		success = true;
		return Action.SUCCESS;
	}

	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}
	
}

For the sake of simplicity we are just printing the submitted data to the console. We have mapped  registerUser method of this class with our form submit action. We will see this in struts.xml file later.

 If you observe this action class is like any other Struts 2 action class. The beauty of struts json plugin is that we no need to make any changes to the action class to return json response. That part is handled by configuring result type to json in struts.xml.

Configuring json plugin with Struts

First you need to download the JSON plugin, if you already don’t have this in your struts download.

To configure json plugin follow the following steps:

  1. Keep the json plugin jar file in the WEB-INF/lib directory of the web project.
  2. In struts.xml, create a new package that extends json-default. If you want to use an existing package then add the json-default as comma separated in the existing package’s extends property.
  3. Define the actions which have to return json response inside the above defined package.
  4. Put the result type as json for the actions to return json response.
After following the above steps the struts.xml would look like the following

<struts>
<package name="default" extends="json-default" namespace="/">					<action name="registerUser" class="sampleapp.action.Registration" method="registerUser">
			<result type="json"/>
		</action>
	</package>
</struts>

Now we are ready to run and test our integration example. When we run the example, the form displayed in first screen shot will come up. Add certain details and hit the ‘Submit’ button, you will see your entered details on the server console.

Handling server side errors

The server side validation can be handled in the similar way as we do for any other struts 2 application. To display validation error against a field of form add the error message in the struts error map. Make sure that the error is added using the field name that is used in Ext JS form panel. Set ‘success’ property in action to false. This makes Ext JS to interpret the response as failure. That is all, nothing else is need to link the error with corresponding form fields. When the above json is returned to the Ext JS form, it will display the error messages against the fields.


Published at DZone with permission of its author, Davinder Singla. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Avinash Sarraff replied on Thu, 2014/07/24 - 1:51am

Great article for extjs integration with Struts. Thanks for posting it.


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.