Collect output in temporary buffer before sending it to the response.
authorDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Thu, 19 Apr 2012 07:31:01 +0000 (09:31 +0200)
committerDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Thu, 19 Apr 2012 07:31:01 +0000 (09:31 +0200)
This has to be this way because HttpServletResponse.getOutputStream()
“commits” the response, making it impossible to set the content type and
encoding later on.

src/main/java/net/pterodactylus/demoscenemusic/core/TemplateServlet.java

index b93fe01..917fad7 100644 (file)
@@ -17,6 +17,8 @@
 
 package net.pterodactylus.demoscenemusic.core;
 
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
@@ -36,6 +38,7 @@ import javax.servlet.http.HttpServletResponse;
 
 import net.pterodactylus.demoscenemusic.page.ServletRequest;
 import net.pterodactylus.util.io.Closer;
+import net.pterodactylus.util.io.StreamCopier;
 import net.pterodactylus.util.template.HtmlFilter;
 import net.pterodactylus.util.template.ReflectionAccessor;
 import net.pterodactylus.util.template.Template;
@@ -121,7 +124,8 @@ public class TemplateServlet extends HttpServlet {
                        } catch (URISyntaxException use1) {
                                throw new IOException("Could not create URI from " + request.getRequestURI(), use1);
                        }
-                       Response response = new Response(httpServletResponse.getOutputStream());
+                       ByteArrayOutputStream responseOutputBuffer = new ByteArrayOutputStream();
+                       Response response = new Response(responseOutputBuffer);
                        response = page.handleRequest(servletRequest, response);
                        for (Header header : response.getHeaders()) {
                                for (String value : header) {
@@ -130,6 +134,7 @@ public class TemplateServlet extends HttpServlet {
                        }
                        httpServletResponse.setContentType(response.getContentType());
                        httpServletResponse.setStatus(response.getStatusCode());
+                       StreamCopier.copy(new ByteArrayInputStream(responseOutputBuffer.toByteArray()), httpServletResponse.getOutputStream());
                        return;
                }
        }