Search code examples
jspstruts2xmlhttprequestactivexobject

How to get struts2 HttpServletReponse using xmlhttp request


My struts.xml part

<action name="viewall" class="com.abc.csm.actions.GetAllConfiguration">
         <result name="success">/success.jsp</result>
    </action>

on Page load of Welcome.jsp i call a function getXml() which should receive xml as a response but instead i get success.jsp content

function getXml()
{
 var url_action="/csm/viewall.action";
 var client; 
 var dataString;

 if (window.XMLHttpRequest){ 
     client=new XMLHttpRequest();
 } else {                    
     client=new ActiveXObject("Microsoft.XMLHTTP");
 }

 client.onreadystatechange=function(){

     if(client.readyState==4&&client.status==200)
     {
         alert(client.responseText); /* here i want to get the actual response i.e., my xml. I am also using fiddler to monitor. */

     }
 };

 dataString="projectid=1-105101";
 client.open("POST",url_action,true);
 client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

 client.send(dataString);
}

Solution

  • In struts.xml you have:

    <result name="success">/success.jsp</result>
    

    This is the same as:

    <result type="dispatcher" name="success">/success.jsp</result>
    

    The dispatcher result type is the default and it means, render the jsp. This is what is happening, you are getting the result of the jsp and not xml.

    Here is a list of the built in result types: http://struts.apache.org/2.0.6/docs/result-types.html The xslt result type may interest you. If you don't mind working in JSON, adding the struts2-json-plugin to your class path gives you the json result type which is very easy to use too.

    Edit: You may also use the stream result.