Search code examples
tomcattomcat7embedded-tomcat-7

Programmatically enable GZIP Tomcat 7 (embedded)


I am using Tomcat7 (embedded)

Something like this...

String APP_DIR = "ROOT";
Tomcat current = new Tomcat();
File file = new File(APP_DIR);
if (file.isDirectory() && file.canRead()) {
    ctx = current.addWebapp(null, "", file.getAbsolutePath());
    ctx.setSessionCookiePathUsesTrailingSlash(false);
}
current.start();
ctx.addServletMapping("*.pdf", "jsp", true);

I have enabled the *.pdf mapping to jsp servlet (some issue I had with IE) is there a way to enable GZIP with this config (I have no web.xml, but if needed I could add to make it work) So far I have only found that I need to add this to my web.xml (which I don't have!)

<Connector port=”8080″ maxHttpHeaderSize=”8192″
maxThreads=”150″ minSpareThreads=”25″ maxSpareThreads=”75″
enableLookups=”false” redirectPort=”8443″ acceptCount=”100″
connectionTimeout=”20000″ disableUploadTimeout=”true”
compression=”on”
compressionMinSize=”2048″
noCompressionUserAgents=”gozilla, traviata”
compressableMimeType=”text/html,text/xml”/>

Solution

  • edit: Updated property compressableMimeType to compressibleMimeType as per comment from pieroxy

    I found that you can setup the properties like this:

    Tomcat current = new Tomcat();
    Connector c = this.current.getConnector();
    c.setProperty("compression", "on");
    c.setProperty("compressionMinSize", "1024");
    c.setProperty("noCompressionUserAgents", "gozilla, traviata");
    c.setProperty("compressibleMimeType", "text/html,text/xml, text/css, application/json, application/javascript");
    

    I guess that this also applies for other connector property that you need to set up.