Serve Gzipped content with Java Servlets

后端 未结 7 2141
予麋鹿
予麋鹿 2021-01-05 01:40

I was wondering if there was an easy way to serve GZipped content with Java Servlets. I already have the app up and running so the modifications needed should be to

相关标签:
7条回答
  • 2021-01-05 02:09

    There are basically 2 ways:

    • Configure it in the appserver. In for example Tomcat you just need to set the compression attribute of the Connector in conf/server.xml to on.
    • Wrap the response.getOutputStream() in a new GzipOutputStream() and write to it instead.

    The first way affects the whole webapp, but this really shouldn't hurt, it's almost zero effort and a big favour for performance. And, more importantingly, as opposed to the second way it actually checks the request headers if the client supports Gzip before using it. When you go for the 2nd way headlessly, then about 10% of the world wide web users wouldn't be able to access your webapplication. This is really not an oneliner task.

    You can find here an advanced example of a FileServlet which supports under each Gzip and checks that based on the request headers. You may get new insights out of it.

    0 讨论(0)
提交回复
热议问题