July 04, 2015

Use AJAX to access JSON from a Struts2 Action class



If there is a use-case wherein a HTTPRequest invokes a Struts2 Action class to perform an action & its output is then to be received by an AJAX function on the target webpage, for e.g.population of data rows in an HTML table, then this is one approach to do it

1. Send the output of the Struts2 Action class as a JSON object. 


 Let's say we have an Action class 'JSONResponseAction.java' that is required to send a Java bean 'ResponseVO.java' ( it has 2 String fields- a status & a message) as a JSON object to client e.g a browser. 

public class JSONResponseAction extends BaseActionSupport
{

public ResponseVO responsVO;


public String load() throws IOException, ServletException
{
   
responseVO=new ResponseVO();
responseVO.setStatus("success");
responsVO.setMessage("Process completed");

}

public ResponseVO  getResponseVO() 
{
    return responseVO;
}

public void setResponseVO(ResponseVO responseVO) 
{
    this.responseVO= responseVO;
}

}

It is mandatory that setter & getter methods be present for 'ResponseVo' bean in the Action class for corresponding JSON object to be created & sent across the n/w. We can also use the default 'execute()' method of Struts2 Action class for this. In that case,We will not have to explicitly mention the method-name in the request URL in pt.3

2. In the struts.xml, we define an action 'JSONResponseAction.action' as follows

  <action name="JSONResponseAction"  class=JSONResponseAction>
  <result name="success" type="json">
     <param name="root">
             responseVO
  </param>
  <result name="failure">/error.jsp</result>
  <interceptor-ref name="defaultStack"/>
 </action>


3. On the client side, we can have JQuery code, something similar to what I have written below, to access 'ResponseVO'.



$.getJSON( "${pageContext.request.contextPath}/JSONResponseAction.action?method:load",
{<requestparamName>:<requestParamvalue>},
function(responseVO) {

     //Jquery or Javascript code to use 'ResponseVO'


});

4. We can also send an array of 'ResponsVO' beans in a similar fashion

public class JSONResponseAction extends BaseActionSupport
{

public ResponseVO[] responseVO;

public String load() throws IOException, ServletException
{
  //populate the array

}
public ResponseVO[]  getResponseVO() 
{
    return responseVO;
}

public void setResponseVO(ResponseVO[] responseVO) 
{
    this.responseVO= responseVO;
}

}


No comments:

Post a Comment