Class GzipHandler
- All Implemented Interfaces:
Handler, GzipFactory, HandlerContainer, Container, Destroyable, Dumpable, Dumpable.DumpableContainer, LifeCycle
The GzipHandler can be applied to the entire server (a gzip.mod is included in
the jetty-home) or it may be applied to individual contexts.
Both Request uncompress and Response compress are gated by a configurable
DispatcherType check on the GzipHandler.
(This is similar in behavior to a Filter configuration
you would find in a Servlet Descriptor file (WEB-INF/web.xml)
(Default: DispatcherType.REQUEST).
Requests with a Content-Encoding header with the value gzip will
be uncompressed by a GzipHttpInputInterceptor for any API that uses
ServletRequest.getInputStream() or ServletRequest.getReader().
Response compression has a number of checks before GzipHandler will perform compression.
-
Does the request contain a
Accept-Encodingheader that specifiesgzipvalue? -
Is the
HttpServletRequest.getMethod()allowed by the configured HTTP Method Filter.
(Default:GET) -
Is the incoming Path allowed by the configured Path Specs filters?
(Default: all paths are allowed) -
Is the Request User-Agent allowed by the configured User-Agent filters?
(Default: MSIE 6 is excluded) -
Is the Response
Content-Lengthheader present, and does its value meet the minimum gzip size requirements (default 32 bytes)? -
Is the Request
Acceptheader present and does it contain the requiredgzipvalue?
When you encounter a configurable filter in the GzipHandler (method, paths, user-agent, mime-types, etc) that has both Included and Excluded values, note that the Included values always win over the Excluded values.
Important note about Default Values: It is important to note that the GzipHandler will automatically configure itself from the MimeType present on the Server, System, and Contexts and the ultimate set of default values for the various filters (paths, methods, mime-types, etc) can be influenced by the available mime types to work with.
ETag (or Entity Tag) information: any Request headers for If-None-Match or
If-Match will be evaluated by the GzipHandler to determine if it was involved
in compression of the response earlier. This is usually present as a --gzip suffix
on the ETag that the Client User-Agent is tracking and handed to the Jetty server.
The special --gzip suffix on the ETag is how GzipHandler knows that the content
passed through itself, and this suffix will be stripped from the Request header values
before the request is sent onwards to the specific webapp / servlet endpoint for
handling.
If a ETag is present in the Response headers, and GzipHandler is compressing the
contents, it will add the --gzip suffix before the Response headers are committed
and sent to the User Agent.
Note that the suffix used is determined by CompressedContentFormat.ETAG_SEPARATOR
This implementation relies on an Jetty internal HttpOutput.Interceptor
mechanism to allow for effective and efficient compression of the response on all Output API usages:
-
ServletOutputStream- Obtained fromServletResponse.getOutputStream()using the traditional Blocking I/O techniques -
WriteListener- Provided toServletOutputStream.setWriteListener(javax.servlet.WriteListener)using the new (since Servlet 3.1) Async I/O techniques -
PrintWriter- Obtained fromServletResponse.getWriter()using Blocking I/O techniques
Historically the compression of responses were accomplished via
Servlet Filters (eg: GzipFilter) and usage of HttpServletResponseWrapper.
Since the introduction of Async I/O in Servlet 3.1, this older form of Gzip support
in web applications has been problematic and bug ridden.
-
Nested Class Summary
Nested classes/interfaces inherited from class AbstractHandler
AbstractHandler.ErrorDispatchHandlerNested classes/interfaces inherited from class AbstractLifeCycle
AbstractLifeCycle.AbstractLifeCycleListenerNested classes/interfaces inherited from interface Container
Container.InheritedListener, Container.ListenerNested classes/interfaces inherited from interface Dumpable
Dumpable.DumpableContainerNested classes/interfaces inherited from interface LifeCycle
LifeCycle.Listener -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final IncludeExclude<String> private booleanDeprecated.feature will be removed in Jetty 10.x, with no replacement.private intprivate DeflaterPoolprivate EnumSet<javax.servlet.DispatcherType> private intprivate final IncludeExclude<String> private final IncludeExclude<String> private intprivate final IncludeExclude<String> private intprivate booleanprivate HttpFieldstatic final intprivate static final Patternstatic final intstatic final Stringstatic final Stringstatic final Stringprivate static final Loggerprivate static final HttpFieldFields inherited from class HandlerWrapper
_handler -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaddExcludedAgentPatterns(String... patterns) Add excluded to the User-Agent filtering.voidaddExcludedMethods(String... methods) Add excluded to the HTTP methods filtering.voidaddExcludedMimeTypes(String... types) Adds excluded MIME types for response filtering.voidaddExcludedPaths(String... pathspecs) Adds excluded Path Specs for request filtering.voidaddIncludedAgentPatterns(String... patterns) Adds included User-Agents for filtering.voidaddIncludedMethods(String... methods) Adds included HTTP Methods (eg: POST, PATCH, DELETE) for filtering.voidaddIncludedMimeTypes(String... types) Add included MIME types for response filteringvoidaddIncludedPaths(String... pathspecs) Add included Path Specs for filtering.protected voiddoStart()Starts the managed lifecycle beans in the order they were added.booleanDeprecated.feature will be removed in Jetty 10.x, with no replacement.intgetDeflater(Request request, long contentLength) intGets the maximum number of Deflaters that the DeflaterPool can hold.EnumSet<javax.servlet.DispatcherType> Get the Set ofDispatcherTypethat this Filter will operate on.String[]Get the current filter list of excluded User-Agent patternsGet the excluded filter list of HTTP methods in CSV formatString[]Get the current filter list of excluded HTTP methodsString[]Get the current filter list of excluded MIME typesString[]Get the current filter list of excluded Path SpecsString[]Get the current filter list of included User-Agent patternsGet the included filter list of HTTP methods in CSV formatString[]Get the current filter list of included HTTP MethodsString[]Get the current filter list of included MIME typesString[]Get the current filter list of included Path SpecsintGet the size (in bytes) of theInflaterbuffer used to inflate compressed requests.String[]Deprecated.usegetIncludedMethods()instead.intGet the minimum size, in bytes, that a responseContent-Lengthmust be before compression will trigger.protected HttpFieldvoidhandle(String target, Request baseRequest, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) Handle a request.protected booleanTest if the provided User-Agent is allowed based on the User-Agent filters.booleanisMimeTypeGzipable(String mimetype) Test if the provided MIME type is allowed based on the MIME type filters.protected booleanisPathGzipable(String requestURI) Test if the provided Request URI is allowed based on the Path Specs filters.booleanIs theDeflaterrunningDeflater.SYNC_FLUSHor not.protected DeflaterPoolnewDeflaterPool(int capacity) voidvoidsetCheckGzExists(boolean checkGzExists) Deprecated.feature will be removed in Jetty 10.x, with no replacement.voidsetCompressionLevel(int compressionLevel) Set the Compression level thatDeflateruses.voidsetDeflaterPoolCapacity(int capacity) Sets the maximum number of Deflaters that the DeflaterPool can hold.voidsetDispatcherTypes(EnumSet<javax.servlet.DispatcherType> dispatchers) Set of supportedDispatcherTypethat this filter will operate on.voidsetDispatcherTypes(javax.servlet.DispatcherType... dispatchers) Set the list of supportedDispatcherTypethat this filter will operate on.voidsetExcludedAgentPatterns(String... patterns) Set the excluded filter list of User-Agent patterns (replacing any previously set)voidsetExcludedMethodList(String csvMethods) Set the excluded filter list of HTTP Methods (replacing any previously set)voidsetExcludedMethods(String... methods) Set the excluded filter list of HTTP methods (replacing any previously set)voidsetExcludedMimeTypes(String... types) Set the excluded filter list of MIME types (replacing any previously set)voidsetExcludedPaths(String... pathspecs) Set the excluded filter list of Path specs (replacing any previously set)voidsetIncludedAgentPatterns(String... patterns) Set the included filter list of User-Agent patterns (replacing any previously set)voidsetIncludedMethodList(String csvMethods) Set the included filter list of HTTP Methods (replacing any previously set)voidsetIncludedMethods(String... methods) Set the included filter list of HTTP methods (replacing any previously set)voidsetIncludedMimeTypes(String... types) Set the included filter list of MIME types (replacing any previously set)voidsetIncludedPaths(String... pathspecs) Set the included filter list of Path specs (replacing any previously set)voidsetInflateBufferSize(int size) Set the size (in bytes) of theInflaterbuffer used to inflate comrpessed requests.voidsetMinGzipSize(int minGzipSize) Set the minimum response size to trigger dynamic compression.voidsetSyncFlush(boolean syncFlush) Set theDeflaterflush mode to use.toString()Methods inherited from class HandlerWrapper
destroy, expandChildren, getHandler, getHandlers, insertHandler, setHandlerMethods inherited from class AbstractHandlerContainer
doShutdown, expandHandler, findContainerOf, getChildHandlerByClass, getChildHandlers, getChildHandlersByClass, setServerMethods inherited from class AbstractHandler
doError, doStop, getServerMethods inherited from class ContainerLifeCycle
addBean, addBean, addEventListener, addManaged, contains, dump, dump, dump, dump, dump, dumpBeans, dumpObject, dumpObjects, dumpStdErr, dumpThis, getBean, getBeans, getBeans, getContainedBeans, getContainedBeans, isAuto, isManaged, isUnmanaged, manage, removeBean, removeBeans, removeEventListener, setBeans, setStopTimeout, start, stop, unmanage, updateBean, updateBean, updateBeansMethods inherited from class AbstractLifeCycle
addLifeCycleListener, getState, getState, getStopTimeout, isFailed, isRunning, isStarted, isStarting, isStopped, isStopping, removeLifeCycleListener, start, stopMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface Dumpable.DumpableContainer
isDumpableMethods inherited from interface LifeCycle
addLifeCycleListener, isFailed, isRunning, isStarted, isStarting, isStopped, isStopping, removeLifeCycleListener, start, stop
-
Field Details
-
GZIP_HANDLER_ETAGS
- See Also:
-
GZIP
- See Also:
-
DEFLATE
- See Also:
-
DEFAULT_MIN_GZIP_SIZE
public static final int DEFAULT_MIN_GZIP_SIZE- See Also:
-
BREAK_EVEN_GZIP_SIZE
public static final int BREAK_EVEN_GZIP_SIZE- See Also:
-
LOG
-
X_CE_GZIP
-
COMMA_GZIP
-
_poolCapacity
private int _poolCapacity -
_deflaterPool
-
_minGzipSize
private int _minGzipSize -
_compressionLevel
private int _compressionLevel -
_checkGzExists
Deprecated.feature will be removed in Jetty 10.x, with no replacement. -
_syncFlush
private boolean _syncFlush -
_inflateBufferSize
private int _inflateBufferSize -
_dispatchers
-
_agentPatterns
-
_methods
-
_paths
-
_mimeTypes
-
_vary
-
-
Constructor Details
-
GzipHandler
public GzipHandler()Instantiates a new GzipHandler.
-
-
Method Details
-
addExcludedAgentPatterns
Add excluded to the User-Agent filtering.- Parameters:
patterns- Regular expressions matching user agents to exclude- See Also:
-
addExcludedMethods
Add excluded to the HTTP methods filtering.- Parameters:
methods- The methods to exclude in compression- See Also:
-
getDispatcherTypes
Get the Set ofDispatcherTypethat this Filter will operate on.- Returns:
- the set of
DispatcherTypethis filter will operate on
-
setDispatcherTypes
Set of supportedDispatcherTypethat this filter will operate on.- Parameters:
dispatchers- the set ofDispatcherTypethat this filter will operate on
-
setDispatcherTypes
public void setDispatcherTypes(javax.servlet.DispatcherType... dispatchers) Set the list of supportedDispatcherTypethat this filter will operate on.- Parameters:
dispatchers- the list ofDispatcherTypethat this filter will operate on
-
addExcludedMimeTypes
Adds excluded MIME types for response filtering.Deprecation Warning: For backward compatibility the MIME types parameters may be comma separated strings, but this will not be supported in future versions of Jetty.
- Parameters:
types- The mime types to exclude (without charset or other parameters).- See Also:
-
addExcludedPaths
Adds excluded Path Specs for request filtering.There are 2 syntaxes supported, Servlet
url-patternbased, and Regex based. This means that the initial characters on the path spec line are very strict, and determine the behavior of the path matching.- If the spec starts with
'^'the spec is assumed to be a regex based path spec and will match with normal Java regex rules. - If the spec starts with
'/'then spec is assumed to be a Servlet url-pattern rules path spec for either an exact match or prefix based match. - If the spec starts with
'*.'then spec is assumed to be a Servlet url-pattern rules path spec for a suffix based match. - All other syntaxes are unsupported
Note: inclusion takes precedence over exclude.
- Parameters:
pathspecs- Path specs (as per servlet spec) to exclude. If a ServletContext is available, the paths are relative to the context path, otherwise they are absolute.
For backward compatibility the pathspecs may be comma separated strings, but this will not be supported in future versions.- See Also:
- If the spec starts with
-
addIncludedAgentPatterns
Adds included User-Agents for filtering.- Parameters:
patterns- Regular expressions matching user agents to include- See Also:
-
addIncludedMethods
Adds included HTTP Methods (eg: POST, PATCH, DELETE) for filtering.- Parameters:
methods- The HTTP methods to include in compression.- See Also:
-
isSyncFlush
public boolean isSyncFlush()Is theDeflaterrunningDeflater.SYNC_FLUSHor not.- Returns:
- True if
Deflater.SYNC_FLUSHis used, elseDeflater.NO_FLUSH - See Also:
-
setSyncFlush
public void setSyncFlush(boolean syncFlush) Set theDeflaterflush mode to use.Deflater.SYNC_FLUSHshould be used if the application wishes to stream the data, but this may hurt compression performance.- Parameters:
syncFlush- True ifDeflater.SYNC_FLUSHis used, elseDeflater.NO_FLUSH- See Also:
-
addIncludedMimeTypes
Add included MIME types for response filtering- Parameters:
types- The mime types to include (without charset or other parameters) For backward compatibility the mimetypes may be comma separated strings, but this will not be supported in future versions.- See Also:
-
addIncludedPaths
Add included Path Specs for filtering.There are 2 syntaxes supported, Servlet
url-patternbased, and Regex based. This means that the initial characters on the path spec line are very strict, and determine the behavior of the path matching.- If the spec starts with
'^'the spec is assumed to be a regex based path spec and will match with normal Java regex rules. - If the spec starts with
'/'then spec is assumed to be a Servlet url-pattern rules path spec for either an exact match or prefix based match. - If the spec starts with
'*.'then spec is assumed to be a Servlet url-pattern rules path spec for a suffix based match. - All other syntaxes are unsupported
Note: inclusion takes precedence over exclusion.
- Parameters:
pathspecs- Path specs (as per servlet spec) to include. If a ServletContext is available, the paths are relative to the context path, otherwise they are absolute
- If the spec starts with
-
doStart
Description copied from class:ContainerLifeCycleStarts the managed lifecycle beans in the order they were added.- Overrides:
doStartin classAbstractHandler- Throws:
Exception
-
getCheckGzExists
Deprecated.feature will be removed in Jetty 10.x, with no replacement. -
getCompressionLevel
public int getCompressionLevel() -
getDeflater
- Specified by:
getDeflaterin interfaceGzipFactory
-
getExcludedAgentPatterns
Get the current filter list of excluded User-Agent patterns- Returns:
- the filter list of excluded User-Agent patterns
- See Also:
-
getExcludedMethods
Get the current filter list of excluded HTTP methods- Returns:
- the filter list of excluded HTTP methods
- See Also:
-
getExcludedMimeTypes
Get the current filter list of excluded MIME types- Returns:
- the filter list of excluded MIME types
- See Also:
-
getExcludedPaths
Get the current filter list of excluded Path Specs- Returns:
- the filter list of excluded Path Specs
- See Also:
-
getIncludedAgentPatterns
Get the current filter list of included User-Agent patterns- Returns:
- the filter list of included User-Agent patterns
- See Also:
-
getIncludedMethods
Get the current filter list of included HTTP Methods- Returns:
- the filter list of included HTTP methods
- See Also:
-
getIncludedMimeTypes
Get the current filter list of included MIME types- Returns:
- the filter list of included MIME types
- See Also:
-
getIncludedPaths
Get the current filter list of included Path Specs- Returns:
- the filter list of included Path Specs
- See Also:
-
getMethods
Deprecated.usegetIncludedMethods()instead. (Will be removed in Jetty 10)Get the current filter list of included HTTP methods- Returns:
- the filter list of included HTTP methods
-
getMinGzipSize
public int getMinGzipSize()Get the minimum size, in bytes, that a responseContent-Lengthmust be before compression will trigger.- Returns:
- minimum response size (in bytes) that triggers compression
- See Also:
-
getVaryField
-
getInflateBufferSize
public int getInflateBufferSize()Get the size (in bytes) of theInflaterbuffer used to inflate compressed requests.- Returns:
- size in bytes of the buffer, or 0 for no inflation.
-
setInflateBufferSize
public void setInflateBufferSize(int size) Set the size (in bytes) of theInflaterbuffer used to inflate comrpessed requests.- Parameters:
size- size in bytes of the buffer, or 0 for no inflation.
-
handle
public void handle(String target, Request baseRequest, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws IOException, javax.servlet.ServletException Description copied from interface:HandlerHandle a request.- Specified by:
handlein interfaceHandler- Overrides:
handlein classHandlerWrapper- Parameters:
target- The target of the request - either a URI or a name.baseRequest- The original unwrapped request object.request- The request either as theRequestobject or a wrapper of that request. Themethod can be used access the Request object if required.HttpConnection.getCurrentConnection().getHttpChannel().getRequest()response- The response as theResponseobject or a wrapper of that request. Themethod can be used access the Response object if required.HttpConnection.getCurrentConnection().getHttpChannel().getResponse()- Throws:
IOException- if unable to handle the request or response processingjavax.servlet.ServletException- if unable to handle the request or response due to underlying servlet issue
-
isAgentGzipable
Test if the provided User-Agent is allowed based on the User-Agent filters.- Parameters:
ua- the user agent- Returns:
- whether compressing is allowed for the given user agent
-
isMimeTypeGzipable
Test if the provided MIME type is allowed based on the MIME type filters.- Specified by:
isMimeTypeGzipablein interfaceGzipFactory- Parameters:
mimetype- the MIME type to test- Returns:
- true if allowed, false otherwise
-
isPathGzipable
Test if the provided Request URI is allowed based on the Path Specs filters.- Parameters:
requestURI- the request uri- Returns:
- whether compressing is allowed for the given the path
-
recycle
- Specified by:
recyclein interfaceGzipFactory
-
setCheckGzExists
Deprecated.feature will be removed in Jetty 10.x, with no replacement.Set the Check if*.gzfile for the incoming file exists.- Parameters:
checkGzExists- whether to check if a static gz file exists for the resource that the DefaultServlet may serve as precompressed.
-
setCompressionLevel
public void setCompressionLevel(int compressionLevel) Set the Compression level thatDeflateruses.- Parameters:
compressionLevel- The compression level to use to initializeDeflater.setLevel(int)- See Also:
-
setExcludedAgentPatterns
Set the excluded filter list of User-Agent patterns (replacing any previously set)- Parameters:
patterns- Regular expressions list matching user agents to exclude- See Also:
-
setExcludedMethods
Set the excluded filter list of HTTP methods (replacing any previously set)- Parameters:
methods- the HTTP methods to exclude- See Also:
-
setExcludedMimeTypes
Set the excluded filter list of MIME types (replacing any previously set)- Parameters:
types- The mime types to exclude (without charset or other parameters)- See Also:
-
setExcludedPaths
Set the excluded filter list of Path specs (replacing any previously set)- Parameters:
pathspecs- Path specs (as per servlet spec) to exclude. If a ServletContext is available, the paths are relative to the context path, otherwise they are absolute.- See Also:
-
setIncludedAgentPatterns
Set the included filter list of User-Agent patterns (replacing any previously set)- Parameters:
patterns- Regular expressions matching user agents to include- See Also:
-
setIncludedMethods
Set the included filter list of HTTP methods (replacing any previously set)- Parameters:
methods- The methods to include in compression- See Also:
-
setIncludedMimeTypes
Set the included filter list of MIME types (replacing any previously set)- Parameters:
types- The mime types to include (without charset or other parameters)- See Also:
-
setIncludedPaths
Set the included filter list of Path specs (replacing any previously set)- Parameters:
pathspecs- Path specs (as per servlet spec) to include. If a ServletContext is available, the paths are relative to the context path, otherwise they are absolute- See Also:
-
setMinGzipSize
public void setMinGzipSize(int minGzipSize) Set the minimum response size to trigger dynamic compression.Sizes below
BREAK_EVEN_GZIP_SIZEwill result a compressed response that is larger than the original data.- Parameters:
minGzipSize- minimum response size in bytes (not allowed to be lower thenBREAK_EVEN_GZIP_SIZE)
-
setIncludedMethodList
Set the included filter list of HTTP Methods (replacing any previously set)- Parameters:
csvMethods- the list of methods, CSV format- See Also:
-
getIncludedMethodList
Get the included filter list of HTTP methods in CSV format- Returns:
- the included filter list of HTTP methods in CSV format
- See Also:
-
setExcludedMethodList
Set the excluded filter list of HTTP Methods (replacing any previously set)- Parameters:
csvMethods- the list of methods, CSV format- See Also:
-
getExcludedMethodList
Get the excluded filter list of HTTP methods in CSV format- Returns:
- the excluded filter list of HTTP methods in CSV format
- See Also:
-
getDeflaterPoolCapacity
public int getDeflaterPoolCapacity()Gets the maximum number of Deflaters that the DeflaterPool can hold.- Returns:
- the Deflater pool capacity
-
setDeflaterPoolCapacity
public void setDeflaterPoolCapacity(int capacity) Sets the maximum number of Deflaters that the DeflaterPool can hold. -
newDeflaterPool
-
toString
- Overrides:
toStringin classAbstractLifeCycle
-