java 如何在 Struts 1.3 中将内容类型 text/xml 输出到浏览器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6874969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I output the content type text/xml to the browser in Struts 1.3
提问by bittersweetryan
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.
我在 Struts 1.3 应用程序中有一个 Ajax 调用,但我无法让它将有效的 XML 返回到浏览器。XML 的内容被正确发送回,但是浏览器仍然将响应类型重新配置为 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.
我目前正在做的只是获取浏览器设置的 XML 字符串并使用 jQuery 的 parseXML() 方法来获取有效的 XML 但这似乎是一种黑客行为,我宁愿让 struts 将响应作为有效的 XML 响应发送回去.
回答by BalusC
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:
至于具体的问题,我不做 Struts,所以我可能是错的,但我想它是有效地将请求转发到 JSP。JspServlet 隐式使用text/html
内容类型。这样,任何基于 servlet 的内容类型更改都将完全无效。在 JSP 中,您需要通过@page
JSP 顶部的声明来设置它,如下所示:
<%@page contentType="text/xml" pageEncoding="UTF-8" %>
(the page encoding is also pretty important, XML markup defaults namely to UTF-8)
(页面编码也很重要,XML 标记默认为 UTF-8)
Don't forget to remove those two lines from your Struts action method.
不要忘记从 Struts 操作方法中删除这两行。