Class ResourceWebHandler
- All Implemented Interfaces:
InitializingBean
,WebHandler
HttpRequestHandler
that serves static resources in an optimized way
according to the guidelines of Page Speed, YSlow, etc.
The "locations" property takes a list of Spring
Resource
locations from which static resources are allowed to
be served by this handler. Resources could be served from a classpath location,
for example, "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:
- 5.0
- Author:
- Rossen Stoyanchev, Brian Clozel, Juergen Hoeller
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionvoid
Invoked by the containingBeanFactory
after it has set all bean properties and satisfiedBeanFactoryAware
,ApplicationContextAware
etc.Return theCacheControl
instance to build the Cache-Control HTTP response header.Return the HTTP ETag generator function to be used when serving resources.Return theList
ofResource
paths to use as sources for serving static resources.Return the configured location values.Return theconfigured
media type mappings.protected reactor.core.publisher.Mono<Resource>
getResource
(ServerWebExchange exchange) Return the configured resource message writer.Return the list of configured resource resolvers.Return the list of configured resource transformers.reactor.core.publisher.Mono<Void>
handle
(ServerWebExchange exchange) 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 boolean
isInvalidPath
(String path) Invoked afterResourceHandlerUtils.isInvalidPath(String)
to allow subclasses to perform further validation.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
setCacheControl
(@Nullable CacheControl cacheControl) Set theCacheControl
instance to build the Cache-Control HTTP response header.void
setEtagGenerator
(@Nullable Function<Resource, String> etagGenerator) Configure a generator function that will be used to create the ETag information, given aResource
that is about to be written to the response.protected void
setHeaders
(ServerWebExchange exchange, Resource resource, @Nullable MediaType mediaType) Set headers on the response.void
setLocations
(@Nullable List<Resource> locations) Set theList
ofResource
paths to use as sources for serving static resources.void
setLocationValues
(List<String> locationValues) Accepts a list of String-based location values to be resolved intoResource
locations.void
setMediaTypes
(Map<String, MediaType> mediaTypes) Add mappings between file extensions extracted from the filename of staticResource
s and the media types to use for 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
setResourceHttpMessageWriter
(@Nullable ResourceHttpMessageWriter httpMessageWriter) Configure theResourceHttpMessageWriter
to use.void
setResourceLoader
(ResourceLoader resourceLoader) Provide the ResourceLoader to loadlocation values
with.void
setResourceResolvers
(@Nullable List<ResourceResolver> resourceResolvers) Configure the list ofResourceResolvers
to use.void
setResourceTransformers
(@Nullable List<ResourceTransformer> resourceTransformers) Configure the list ofResourceTransformers
to use.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()
-
Constructor Details
-
ResourceWebHandler
public ResourceWebHandler()
-
-
Method Details
-
setResourceLoader
Provide the ResourceLoader to loadlocation values
with.- Since:
- 5.1
-
setLocationValues
Accepts a list of String-based location values to be resolved intoResource
locations.- Since:
- 5.1
-
getLocationValues
Return the configured location values.- Since:
- 5.1
-
setLocations
Set theList
ofResource
paths to use as sources for serving static resources. -
getLocations
Return theList
ofResource
paths to use as sources for serving static resources.Note that if
locationValues
are provided, instead of loaded Resource-based locations, this method will return empty until after initialization viaafterPropertiesSet()
.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. -
setResourceHttpMessageWriter
Configure theResourceHttpMessageWriter
to use.By default a
ResourceHttpMessageWriter
will be configured. -
getResourceHttpMessageWriter
Return the configured resource message writer. -
setCacheControl
Set theCacheControl
instance to build the Cache-Control HTTP response header. -
getCacheControl
Return theCacheControl
instance to build the Cache-Control HTTP response header. -
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
-
setEtagGenerator
Configure a generator function that will be used to create the ETag information, given aResource
that is about to be written to the response.This function should return a String that will be used as an argument in
ServerWebExchange.checkNotModified(String)
, ornull
if no value can be generated for the given resource.- Parameters:
etagGenerator
- the HTTP ETag generator function to use.- Since:
- 6.1
-
getEtagGenerator
Return the HTTP ETag generator function to be used when serving resources.- Returns:
- the HTTP ETag generator function
- Since:
- 6.1
-
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
-
setMediaTypes
Add mappings between file extensions extracted from the filename of staticResource
s and the media types to use for the response.Use of this method is typically not necessary since mappings can be also determined via
MediaTypeFactory.getMediaType(Resource)
.- Parameters:
mediaTypes
- media type mappings- Since:
- 5.3.2
-
getMediaTypes
Return theconfigured
media type mappings.- Since:
- 5.3.2
-
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. -
handle
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:
handle
in interfaceWebHandler
- Parameters:
exchange
- the current server exchange- Returns:
Mono<Void>
to indicate when request handling is complete
-
getResource
-
processPath
Process the given resource path.By default, this method delegates to
ResourceHandlerUtils.normalizeInputPath(java.lang.String)
. -
isInvalidPath
Invoked afterResourceHandlerUtils.isInvalidPath(String)
to allow subclasses to perform further validation.By default, this method does not perform any validations.
-
setHeaders
protected void setHeaders(ServerWebExchange exchange, Resource resource, @Nullable MediaType mediaType) throws IOException Set headers on the response. Called for both GET and HEAD requests.- Parameters:
exchange
- current exchangeresource
- the identified resource (nevernull
)mediaType
- the resource's media type (nevernull
)- Throws:
IOException
-
toString
-