Class ResourceHttpRequestHandler
- All Implemented Interfaces:
Aware
,InitializingBean
,ApplicationContextAware
,EmbeddedValueResolverAware
,ServletContextAware
,CorsConfigurationSource
,HttpRequestHandler
HttpRequestHandler
that serves static resources in an optimized way
according to the guidelines of Page Speed, YSlow, etc.
The properties "locations" and "locationValues" accept locations from which static resources can be served by this handler. This can be relative to the root of the web application, or from the classpath, e.g. "classpath:/META-INF/public-web-resources/", allowing convenient packaging and serving of resources such as .js, .css, and others in jar files.
This request handler may also be configured with a
resourcesResolver
and
resourceTransformer
chains to support
arbitrary resolution and transformation of resources being served. By default,
a PathResourceResolver
simply finds resources based on the configured
"locations". An application can configure additional resolvers and transformers
such as the VersionResourceResolver
which can resolve and prepare URLs
for resources with a version in the URL.
This handler also properly evaluates the Last-Modified
header
(if present) so that a 304
status code will be returned as appropriate,
avoiding unnecessary overhead for resources that are already cached by the client.
- Since:
- 3.0.4
- Author:
- Keith Donald, Jeremy Grelle, Juergen Hoeller, Arjen Poutsma, Brian Clozel, Rossen Stoyanchev
-
Field Summary
Fields inherited from class org.springframework.web.servlet.support.WebContentGenerator
HEADER_CACHE_CONTROL, METHOD_GET, METHOD_HEAD, METHOD_POST
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionvoid
Invoked by the containingBeanFactory
after it has set all bean properties and satisfiedBeanFactoryAware
,ApplicationContextAware
etc.Deprecated.as of 5.2.4getCorsConfiguration
(HttpServletRequest request) Return the specified CORS configuration.Return the configuredList
ofResource
locations including both String-based locations provided viasetLocationValues
and pre-resolvedResource
locations provided viasetLocations
.protected MediaType
getMediaType
(HttpServletRequest request, Resource resource) Determine the media type for the given request and the resource matched to it.Return theconfigured
media types.protected Resource
getResource
(HttpServletRequest request) Return the configured resource converter.Return the configured resource region converter.Return the list of configured resource resolvers.Return the list of configured resource transformers.The configuredUrlPathHelper
.void
handleRequest
(HttpServletRequest request, HttpServletResponse response) Processes a resource request.protected void
Look for aPathResourceResolver
among the configured resource resolvers and set itsallowedLocations
property (if empty) to match thelocations
configured on this class.protected PathExtensionContentNegotiationStrategy
Deprecated.as of 5.2.4 this method returnsnull
, and if a subclass returns an actual instance, the instance is used only as a source of media type mappings, if it contains any.protected boolean
isInvalidPath
(String path) Identifies invalid resource paths.boolean
Return whether to optimize the specified locations through an existence check on startup, filtering non-existing directories upfront so that they do not have to be checked on every resource access.boolean
Return whether theResource.lastModified()
information is used to drive HTTP responses when serving static resources.protected String
processPath
(String path) Process the given resource path.void
setContentNegotiationManager
(ContentNegotiationManager contentNegotiationManager) Deprecated.as of 5.2.4 in favor of usingsetMediaTypes(Map)
with mappings possibly obtained fromContentNegotiationManager.getMediaTypeMappings()
.void
setCorsConfiguration
(CorsConfiguration corsConfiguration) Specify the CORS configuration for resources served by this handler.void
setEmbeddedValueResolver
(StringValueResolver resolver) Set the StringValueResolver to use for resolving embedded definition values.protected void
setHeaders
(HttpServletResponse response, Resource resource, MediaType mediaType) Set headers on the given servlet response.void
setLocations
(List<Resource> locations) Configure locations to serve resources from as pre-resourced Resource's.void
setLocationValues
(List<String> locations) Configure String-based locations to serve resources from.void
setMediaTypes
(Map<String, MediaType> mediaTypes) Add mappings between file extensions, extracted from the filename of a staticResource
, and corresponding media type to set on the response.void
setOptimizeLocations
(boolean optimizeLocations) Set whether to optimize the specified locations through an existence check on startup, filtering non-existing directories upfront so that they do not have to be checked on every resource access.void
setResourceHttpMessageConverter
(ResourceHttpMessageConverter messageConverter) Configure theResourceHttpMessageConverter
to use.void
setResourceRegionHttpMessageConverter
(ResourceRegionHttpMessageConverter messageConverter) Configure theResourceRegionHttpMessageConverter
to use.void
setResourceResolvers
(List<ResourceResolver> resourceResolvers) Configure the list ofResourceResolvers
to use.void
setResourceTransformers
(List<ResourceTransformer> resourceTransformers) Configure the list ofResourceTransformers
to use.void
setUrlPathHelper
(UrlPathHelper urlPathHelper) Provide a reference to theUrlPathHelper
used to map requests to static resources.void
setUseLastModified
(boolean useLastModified) Set whether we should look at theResource.lastModified()
when serving resources and use this information to drive"Last-Modified"
HTTP response headers.toString()
Methods inherited from class org.springframework.web.servlet.support.WebContentGenerator
applyCacheControl, applyCacheSeconds, applyCacheSeconds, cacheForSeconds, cacheForSeconds, checkAndPrepare, checkRequest, getAllowHeader, getCacheControl, getCacheSeconds, getSupportedMethods, getVaryByRequestHeaders, isAlwaysMustRevalidate, isRequireSession, isUseCacheControlHeader, isUseCacheControlNoStore, isUseExpiresHeader, prepareResponse, preventCaching, setAlwaysMustRevalidate, setCacheControl, setCacheSeconds, setRequireSession, setSupportedMethods, setUseCacheControlHeader, setUseCacheControlNoStore, setUseExpiresHeader, setVaryByRequestHeaders
Methods inherited from class org.springframework.web.context.support.WebApplicationObjectSupport
getServletContext, getTempDir, getWebApplicationContext, initApplicationContext, initServletContext, isContextRequired, setServletContext
Methods inherited from class org.springframework.context.support.ApplicationObjectSupport
getApplicationContext, getMessageSourceAccessor, initApplicationContext, obtainApplicationContext, requiredContextClass, setApplicationContext
-
Constructor Details
-
ResourceHttpRequestHandler
public ResourceHttpRequestHandler()
-
-
Method Details
-
setLocationValues
Configure String-based locations to serve resources from.For example, {
"/"
,"classpath:/META-INF/public-web-resources/"
} allows resources to be served both from the web application root and from any JAR on the classpath that contains a/META-INF/public-web-resources/
directory, with resources in the web application root taking precedence.For
URL-based resources
(e.g. files, HTTP URLs, etc) this method supports a special prefix to indicate the charset associated with the URL so that relative paths appended to it can be encoded correctly, for example"[charset=Windows-31J]https://example.org/path"
.- Since:
- 4.3.13
- See Also:
-
setLocations
Configure locations to serve resources from as pre-resourced Resource's.- See Also:
-
getLocations
Return the configuredList
ofResource
locations including both String-based locations provided viasetLocationValues
and pre-resolvedResource
locations provided viasetLocations
.Note that the returned list is fully initialized only after initialization via
afterPropertiesSet()
.Note: As of 5.3.11 the list of locations may be filtered to exclude those that don't actually exist and therefore the list returned from this method may be a subset of all given locations. See
setOptimizeLocations(boolean)
. -
setResourceResolvers
Configure the list ofResourceResolvers
to use.By default
PathResourceResolver
is configured. If using this property, it is recommended to addPathResourceResolver
as the last resolver. -
getResourceResolvers
Return the list of configured resource resolvers. -
setResourceTransformers
Configure the list ofResourceTransformers
to use.By default no transformers are configured for use.
-
getResourceTransformers
Return the list of configured resource transformers. -
setResourceHttpMessageConverter
public void setResourceHttpMessageConverter(@Nullable ResourceHttpMessageConverter messageConverter) Configure theResourceHttpMessageConverter
to use.By default a
ResourceHttpMessageConverter
will be configured.- Since:
- 4.3
-
getResourceHttpMessageConverter
Return the configured resource converter.- Since:
- 4.3
-
setResourceRegionHttpMessageConverter
public void setResourceRegionHttpMessageConverter(@Nullable ResourceRegionHttpMessageConverter messageConverter) Configure theResourceRegionHttpMessageConverter
to use.By default a
ResourceRegionHttpMessageConverter
will be configured.- Since:
- 4.3
-
getResourceRegionHttpMessageConverter
Return the configured resource region converter.- Since:
- 4.3
-
setContentNegotiationManager
@Deprecated public void setContentNegotiationManager(@Nullable ContentNegotiationManager contentNegotiationManager) Deprecated.as of 5.2.4 in favor of usingsetMediaTypes(Map)
with mappings possibly obtained fromContentNegotiationManager.getMediaTypeMappings()
.Configure aContentNegotiationManager
to help determine the media types for resources being served. If the manager contains a path extension strategy it will be checked for registered file extension.- Since:
- 4.3
-
getContentNegotiationManager
Deprecated.as of 5.2.4Return the configured content negotiation manager.- Since:
- 4.3
-
setMediaTypes
Add mappings between file extensions, extracted from the filename of a staticResource
, and corresponding media type to set on the response.Use of this method is typically not necessary since mappings are otherwise determined via
ServletContext.getMimeType(String)
or viaMediaTypeFactory.getMediaType(Resource)
.- Parameters:
mediaTypes
- media type mappings- Since:
- 5.2.4
-
getMediaTypes
Return theconfigured
media types.- Since:
- 5.2.4
-
setCorsConfiguration
Specify the CORS configuration for resources served by this handler.By default this is not set in which allows cross-origin requests.
-
getCorsConfiguration
Return the specified CORS configuration.- Specified by:
getCorsConfiguration
in interfaceCorsConfigurationSource
- Returns:
- the associated
CorsConfiguration
, ornull
if none
-
setUrlPathHelper
Provide a reference to theUrlPathHelper
used to map requests to static resources. This helps to derive information about the lookup path such as whether it is decoded or not.- Since:
- 4.3.13
-
getUrlPathHelper
The configuredUrlPathHelper
.- Since:
- 4.3.13
-
setUseLastModified
public void setUseLastModified(boolean useLastModified) Set whether we should look at theResource.lastModified()
when serving resources and use this information to drive"Last-Modified"
HTTP response headers.This option is enabled by default and should be turned off if the metadata of the static files should be ignored.
- Since:
- 5.3
-
isUseLastModified
public boolean isUseLastModified()Return whether theResource.lastModified()
information is used to drive HTTP responses when serving static resources.- Since:
- 5.3
-
setOptimizeLocations
public void setOptimizeLocations(boolean optimizeLocations) Set whether to optimize the specified locations through an existence check on startup, filtering non-existing directories upfront so that they do not have to be checked on every resource access.The default is
false
, for defensiveness against zip files without directory entries which are unable to expose the existence of a directory upfront. Switch this flag totrue
for optimized access in case of a consistent jar layout with directory entries.- Since:
- 5.3.13
-
isOptimizeLocations
public boolean isOptimizeLocations()Return whether to optimize the specified locations through an existence check on startup, filtering non-existing directories upfront so that they do not have to be checked on every resource access.- Since:
- 5.3.13
-
setEmbeddedValueResolver
Description copied from interface:EmbeddedValueResolverAware
Set the StringValueResolver to use for resolving embedded definition values.- Specified by:
setEmbeddedValueResolver
in interfaceEmbeddedValueResolverAware
-
afterPropertiesSet
Description copied from interface:InitializingBean
Invoked by the containingBeanFactory
after it has set all bean properties and satisfiedBeanFactoryAware
,ApplicationContextAware
etc.This method allows the bean instance to perform validation of its overall configuration and final initialization when all bean properties have been set.
- Specified by:
afterPropertiesSet
in interfaceInitializingBean
- Throws:
Exception
- in the event of misconfiguration (such as failure to set an essential property) or if initialization fails for any other reason
-
initAllowedLocations
protected void initAllowedLocations()Look for aPathResourceResolver
among the configured resource resolvers and set itsallowedLocations
property (if empty) to match thelocations
configured on this class. -
initContentNegotiationStrategy
@Nullable @Deprecated protected PathExtensionContentNegotiationStrategy initContentNegotiationStrategy()Deprecated.as of 5.2.4 this method returnsnull
, and if a subclass returns an actual instance, the instance is used only as a source of media type mappings, if it contains any. Please, usesetMediaTypes(Map)
instead, or if you need to change behavior, you can overridegetMediaType(HttpServletRequest, Resource)
.Initialize the strategy to use to determine the media type for a resource. -
handleRequest
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException Processes a resource request.Checks for the existence of the requested resource in the configured list of locations. If the resource does not exist, a
404
response will be returned to the client. If the resource exists, the request will be checked for the presence of theLast-Modified
header, and its value will be compared against the last-modified timestamp of the given resource, returning a304
status code if theLast-Modified
value is greater. If the resource is newer than theLast-Modified
value, or the header is not present, the content resource of the resource will be written to the response with caching headers set to expire one year in the future.- Specified by:
handleRequest
in interfaceHttpRequestHandler
- Parameters:
request
- current HTTP requestresponse
- current HTTP response- Throws:
ServletException
- in case of general errorsIOException
- in case of I/O errors
-
getResource
- Throws:
IOException
-
processPath
Process the given resource path.The default implementation replaces:
- Backslash with forward slash.
- Duplicate occurrences of slash with a single slash.
- Any combination of leading slash and control characters (00-1F and 7F)
with a single "/" or "". For example
" / // foo/bar"
becomes"/foo/bar"
.
- Since:
- 3.2.12
-
isInvalidPath
Identifies invalid resource paths. By default, rejects:- Paths that contain "WEB-INF" or "META-INF"
- Paths that contain "../" after a call to
StringUtils.cleanPath(java.lang.String)
. - Paths that represent a
valid URL
or would represent one after the leading slash is removed.
Note: this method assumes that leading, duplicate '/' or control characters (e.g. white space) have been trimmed so that the path starts predictably with a single '/' or does not have one.
- Parameters:
path
- the path to validate- Returns:
true
if the path is invalid,false
otherwise- Since:
- 3.0.6
-
getMediaType
Determine the media type for the given request and the resource matched to it. This implementation tries to determine the MediaType using one of the following lookups based on the resource filename and its path extension:- Parameters:
request
- the current requestresource
- the resource to check- Returns:
- the corresponding media type, or
null
if none found
-
setHeaders
protected void setHeaders(HttpServletResponse response, Resource resource, @Nullable MediaType mediaType) throws IOException Set headers on the given servlet response. Called for GET requests as well as HEAD requests.- Parameters:
response
- current servlet responseresource
- the identified resource (nevernull
)mediaType
- the resource's media type (nevernull
)- Throws:
IOException
- in case of errors while setting the headers
-
toString
-