From: David ‘Bombe’ Roden Date: Thu, 19 Apr 2012 07:31:01 +0000 (+0200) Subject: Collect output in temporary buffer before sending it to the response. X-Git-Url: https://git.pterodactylus.net/?a=commitdiff_plain;h=a0060f0995fc196a6890905e01466501ad401323;p=demoscenemusic.git Collect output in temporary buffer before sending it to the response. This has to be this way because HttpServletResponse.getOutputStream() “commits” the response, making it impossible to set the content type and encoding later on. --- diff --git a/src/main/java/net/pterodactylus/demoscenemusic/core/TemplateServlet.java b/src/main/java/net/pterodactylus/demoscenemusic/core/TemplateServlet.java index b93fe01..917fad7 100644 --- a/src/main/java/net/pterodactylus/demoscenemusic/core/TemplateServlet.java +++ b/src/main/java/net/pterodactylus/demoscenemusic/core/TemplateServlet.java @@ -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; } }