3

I know I can gzip the output stream by using something like..


OutputStream outA = response.getOutputStream();
outWriter = new PrintWriter(new GZIPOutputStream(outA), false);      
response.setHeader("Content-Encoding", "gzip");
outWriter.println(.....);
outWriter.close();

in a JSP, but is it possible to write it as:

OutputStream outA = response.getOutputStream();
outWriter = new PrintWriter(new GZIPOutputStream(outA), false);      
response.setHeader("Content-Encoding", "gzip");
%>
...

I know this is done in PHP for example by capturing the output buffer before it is flushed, gzipping the buffer, and then finally writing it.

But is it possible in a JSP?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
jerluc
  • 4,186
  • 2
  • 25
  • 44

1 Answers1

6

This Java code doesn't belong in a JSP.

If your intent is to gzip the HTML code generated by JSP, then you need to configure it at appserver level. In JBoss (and Tomcat) you need to set the compression attribute of the <Connector> element in /server.xml to on.

<Connector compression="on">

That's all. It'll be by default applied on all text/* responses (HTML/CSS/JS).

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Hm, well I just tried altering the http connector in my jbossweb.sar/server.xml (I'm assuming to be the equivalent), and it seems to be working so far! – jerluc Jan 28 '11 at 19:32
  • You're welcome. Indeed, it'll work the same way on JBoss since its servletcontainer part is basically a slight modified fork of Tomcat. You can if necessary alter `compressableMimeTypes` whenever you want to cover more than only `text/*`, for example `application/json` which is in essence also text based response. – BalusC Jan 28 '11 at 19:34
  • Thanks for the tips and also the link to your blog post was helpful too – jerluc Jan 28 '11 at 19:38
  • +1 Thanks a lot. This is a quick fix and quality information. However, is there anything I can do to gzip my content when I do not have access to the server files? On my local host this option is great but when I take my site to a godaddy shared VPS I will not have access to the server.xml file. Any pointers on what I could do then? – gmustudent Mar 29 '13 at 09:55
  • 1
    @gmu: You could use a servlet filter for this. The JSF utility library OmniFaces, which is maintained by me, has also such a filter which is also reusable on "plain" JSP/Servlet webapps and even in combination with other frameworks than JSF: http://showcase.omnifaces.org/filters/GzipResponseFilter Other filters are listed in this question http://stackoverflow.com/q/4755302/ – BalusC Mar 29 '13 at 11:35
  • And your blog was a great read btw. It was nice seeing advice on how to make a website faster that was not geared towards the php developer. – gmustudent Mar 29 '13 at 22:42