Aug 2, 2013

Making AJAX Call in Struts 2

This may be very obvious thing but still this may help newbies in struts 2 and equally applicable for Struts 1.

So lets take a simple example. We will select a country and AJAX call will get following details in a tabular form from DB and populate it on our screen. Simple isn't it?

So first lets create our html file that will have a drop down for countries (this too can be made AJAX filled drop down but lets keep it for self learning)


Once this html is ready lets add an entry in our configuration file for Action to be called from our js function.

Now we will create one JSP which will return response text to our html file which initially sent the AJAX request.

Now we will create one Action class and for the sack of brevity we will just return the flow to jsp created in last step and see what happens.

If you are able to understand the complete flow from this can skip remaining part else go ahead :).

So here is what happened.
  • HTML file requested for AJAX request XMLHttpRequest
  • XMLHttpRequest was made to .action url and App server realizes that this will be handled by Something called Filter dispatcher of Struts2 and sends it to dispatcher class.
  • Dispatcher class identifies which action class is mapped with this action and passes request to it.
  • Action class simply routes the flow to JSP file which will create response for this requests and returns it to Strut 2 dispatcher class via different interceptors.
  • Dispatcher returns this response to XMLHttpRequest in browser and there it (response in terms of text) is returned to javascript which made this call.
  • Javascript gets this text and flushes in to particular html object and since your browser understands this html text it displays you nice tabular format.
So lets move ahead and create our Service classes and DAO class which will actually return us some data to be displayed on screen.