Serve Gzipped content with Java Servlets

后端 未结 7 2144
予麋鹿
予麋鹿 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 01:58

    Just wanted to let you know what I ended doing.

    I made a wrapper of the request class that looks like this:

    public class GzippedResponse extends HttpServletResponseWrapper{
    
      private PrintWriter pw;
    
      private GzippedResponse(HttpServletResponse response){
        super(response);
        try{
          pw = new PrintWriter(new GZIPOutputStream(response.getOutputStream()));
        }catch(Exception e){
          throw new ApiInternalException("Failed to create a Gzipped Response", e);
        }
      }
    
      public static GzippedResponse wrap(HttpServletResponse response){
        return new GzippedResponse(response);
      }
    
      @Override
      public PrintWriter getWriter() throws IOException {
        return pw;
      }  
    }
    

    And then on my BaseAction, which is basically a TemplateMethod for other "Actions" I wrap the response like this:

    if(supportsCompression(request)){
      response.setHeader("Content-Encoding", "gzip");
      response = GzippedResponse.wrap(response);
    }
    action.macroExecute(request,response);
    

    I think its clean enough. If you find something that can be improved, please let me know. Thanks everybody for the answers!

提交回复
热议问题