1

我正在尝试将 XML 文档呈现给浏览器,但我得到一个空白屏幕。但是,当我查看页面的源代码时,我可以看到 XML。

@RequestMapping(value = "view-xml", method = {RequestMethod.GET})
public ResponseEntity<String> viewXmlPayload(@RequestParam ("id") int taskId){

    payload = dao.getXmlPayload(taskId);

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.TEXT_XML);
    return new ResponseEntity<String>(payload, responseHeaders, HttpStatus.OK);
}

使用一些浏览器工具,我可以看到内容类型已正确设置为“text/xml”,但我仍然没有在页面上看到任何内容。

4

3 回答 3

0

来自RFC 3023

If an XML document -- that is, the unprocessed, source XML document -- is readable by
casual users, text/xml is preferable to application/xml. MIME user agents (and web user
agents) that do not have explicit support for text/xml will treat it as text/plain, for 
example, by displaying the XML MIME entity as plain text. Application/xml is preferable when the XML MIME entity is unreadable by casual users.

您的代码可能没有问题,有些browser根本不呈现 XML。而不是text/xml,您需要使用application/xml

为什么要尝试将 XML 文档呈现给浏览器,如果仍要呈现,请使用XSLT将.XMLHTML

于 2013-09-13T11:40:32.833 回答
0

您可以使用 XML Marshaller http://docs.spring.io/spring-ws/site/reference/html/oxm.html 或手动使用这样的常用库:

    @RequestMapping("/downloadXML.do")
public ModelAndView downloadXML(HttpServletResponse  response,@RequestParam("xmlName") String xmlName ) {   

String doc=serviceXml.getXml(xmlName);      

    InputStream in = null;
    try {
        response.setHeader("Content-Disposition", "filename=\"" +doc.getFilename()+ "\"");
        OutputStream out = response.getOutputStream();
        response.setContentType(doc.getContentType());
        in = doc.getInputStream();
        IOUtils.copy(in, out);
        out.flush();
        out.close();


    } catch (IOException e) {
        e.printStackTrace();
    }
    finally 
    {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
return null;
}
于 2013-09-13T12:06:52.480 回答
0

尝试以下两项:

  1. 将内容类型设置为“text/xml”。您可以在控制器请求处理程序方法中执行此操作 -->response.setContentType("text/xml");或者如果您的 xml 内容位于单独的 JSP 文件中,请将<%@ page contentType="text/xml" %>指令设置在顶部。
  2. 确保在 applicationContext.xml 中,在 viewResolver bean 配置中添加了以下属性。 <property name="alwaysInclude" value="true" />.
于 2016-09-01T19:02:13.383 回答