【问题标题】:Reading xsl from jsp从jsp读取xsl
【发布时间】:2012-05-12 11:54:45
【问题描述】:

我想从 xml 文件打开流,然后在 jsp 文件中使用 xsl 转换。一切似乎都是正确的,但我不知道为什么当我从响应中获取输出时会出现异常。

这是我的代码

<%@page import="javax.xml.transform.*" %>
<%@page import="javax.xml.transform.stream.*" %>
<%@page import="java.io.*" %>
<%

StreamSource xmlSource = new StreamSource( new File(application.getRealPath("foo/cd.xml")));
StreamSource xsltSource = new StreamSource( new File(application.getRealPath("foo/cd.xsl")));

StreamResult fileResult = new StreamResult(response.getOutputStream());
try {
    // Load a Transformer object and perform the transformation
    TransformerFactory tfFactory = TransformerFactory.newInstance();
    Transformer tf = tfFactory.newTransformer(xsltSource);
    tf.transform(xmlSource, fileResult);
} catch(TransformerException e) {
    throw new ServletException("Transforming XML failed.", e);
}

%>

例外情况是:java.lang.IllegalStateException: getOutputStream() 已为此响应调用

那么我该如何摆脱它。谢谢

【问题讨论】:

    标签: xml jsp xslt


    【解决方案1】:

    Jstl 包含用于进行 xsl 转换的 jsp 标签。这使您可以选择执行转换,而不必担心输出流。

    Sun 提供了一个转换示例here。因此,如果您的战争中有 jstl:

    <%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    
    <c:import url="foo/cd.xml" var="xmldocument"/>
    <c:import url="foo/cd.xsl" var="xslt"/>
    <x:transform xml="${xmldocument}" xslt="${xslt}"/>
    

    另一个例子是here

    tomcat examples.war web 应用程序包含 jstl。

    【讨论】:

      【解决方案2】:

      当 JSP 执行时,它会打开响应编写器以将其第一个字符写入文本(所有 %@page ... %> 指令之间的换行符)。然后您尝试打开响应的输出流,但 JSP 之前已经完成了它。

      这种纯Java代码没有理由放在JSP中,JSP是为了使用JSP标签生成标记。使用 servlet 来做到这一点。

      【讨论】:

      • 这是一个完全愚蠢的要求。你用锤子打螺丝吗?
      【解决方案3】:

      我正在尝试来自 pd40 的解决方案,但它不起作用。这些库导入反而起作用了:

      <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
      <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
      

      见:https://stackoverflow.com/a/19434154/1590763

      【讨论】:

        猜你喜欢
        • 2011-05-08
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 2012-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        相关资源
        最近更新 更多