Reputation: 313
I want to open the stream from xml file, then use xsl tranformation in a jsp file. Everything seems correct, but I dont know why there is an exception when I getOutput from response.
This is my code
<%@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);
}
%>
The exception is : java.lang.IllegalStateException: getOutputStream() has already been called for this response
So how can i get rid of that. Thanks
Upvotes: 0
Views: 3774
Reputation: 742
I was trying the solution from pd40, but it wasn't working. These library imports worked instead:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
See: https://stackoverflow.com/a/19434154/1590763
Upvotes: 0
Reputation: 3257
Jstl includes jsp tags for doing an xsl transform. This gives you the option of performing a transform without having to worry about output streams.
Sun provides a transform example here. So if you have jstl in your war:
<%@ 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}"/>
Another example is here
The tomcat examples.war web app includes jstl.
Upvotes: 1
Reputation: 691893
When the JSP is executed, it opens the response writer to write its first characters as text (the newline chars between all your <%@page ... %>
directives). You then try to open the output stream of the response, but the JSP has already done it before.
This kind of pure Java code has no reason to be put in a JSP, which is meant to generate markup using JSP tags. Use a servlet to do that.
Upvotes: 0