【问题标题】:Displaying XML String with Spring MVC使用 Spring MVC 显示 XML 字符串
【发布时间】:2013-09-18 02:00:32
【问题描述】:

我正在尝试将 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”,但我仍然没有在页面上看到任何内容。

【问题讨论】:

  • 您的意思是响应是空白的(即使您查看源代码)?
  • @Manish 页面什么也不显示,但是当我查看源代码时,我可以看到 XML。

标签: java xml spring spring-mvc web


【解决方案1】:

试试以下两个项目:

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

【讨论】:

    【解决方案2】:

    你可以使用 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;
    }
    

    【讨论】:

      【解决方案3】:

      来自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 文档,如果仍要渲染,请使用 XSLTXML 转换为 HTML

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 2015-01-09
        • 2017-10-25
        • 2017-12-07
        • 1970-01-01
        • 2019-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多