javaxmlstruts-1

How do I output the content type text/xml to the browser in Struts 1.3


I have an Ajax call in a Struts 1.3 application and I'm having trouble getting it to return valid XML to the browser. The content of the XML is being sent back correct, however the browser still reconizes the response type as text/html.

My action class looks like this:

 public ActionForward newContractCAUAjax(ActionMapping actionMapping,
        ActionForm actionForm, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse)throws Exception {

    String target="forwardToCAUXML";

    DynaActionForm dynaActionForm = (DynaActionForm) actionForm;

    httpServletResponse.setContentType("text/xml");
    httpServletResponse.setHeader("Content-type","application/xhtml+xml");

    ...

    return actionMapping.findForward(target);
}

What I'm currently doing is just grabbing the XML string that the browser sets back and using jQuery's parseXML() method to get valid XML but this seems like a hack and I'd rather have struts send the response back as a valid XML response.


Solution

  • httpServletResponse.setContentType("text/xml");
    httpServletResponse.setHeader("Content-type","application/xhtml+xml");
    

    This makes no sense The second line overrides the first one with the wrong content type.

    As to the concrete problem, I don't do Struts so I may be wrong, but I'd imagine that it's effectively forwarding the request to a JSP. The JspServlet implicitly uses text/html content type. This way any servlet-based content type change will have total no effect. In a JSP, you would need to set it by the @page declaration in top of JSP as follows:

    <%@page contentType="text/xml" pageEncoding="UTF-8" %>
    

    (the page encoding is also pretty important, XML markup defaults namely to UTF-8)

    Don't forget to remove those two lines from your Struts action method.