Top Description Fields Constructors Methods
org.springframework.web.reactive.resource

public Class ResourceWebHandler

extends Object
implements WebHandler, InitializingBean
Class Inheritance
All Implemented Interfaces
org.springframework.beans.factory.InitializingBean, org.springframework.web.server.WebHandler
Imports
java.io.IOException, java.net.URLDecoder, java.nio.charset.StandardCharsets, java.time.Instant, java.util.ArrayList, .Collections, .HashMap, .List, .Locale, .Map, .Set, java.util.function.Function, org.apache.commons.logging.Log, .LogFactory, reactor.core.publisher.Mono, org.springframework.beans.factory.InitializingBean, org.springframework.core.ResolvableType, org.springframework.core.codec.Hints, org.springframework.core.io.Resource, .ResourceLoader, org.springframework.core.log.LogFormatUtils, org.springframework.http.CacheControl, .HttpHeaders, .HttpMethod, .MediaType, .MediaTypeFactory, org.springframework.http.codec.ResourceHttpMessageWriter, org.springframework.http.server.PathContainer, org.springframework.lang.Nullable, org.springframework.util.Assert, .CollectionUtils, .ObjectUtils, .ResourceUtils, .StringUtils, org.springframework.web.reactive.HandlerMapping, org.springframework.web.server.MethodNotAllowedException, .ServerWebExchange, .WebHandler, org.springframework.web.util.pattern.PathPattern

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, 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.

Authors
Rossen Stoyanchev, Brian Clozel, Juergen Hoeller
Since
5.0

Field Summary

Modifier and TypeField and Description
private CacheControl
private Function<Resource, String>
private final List<Resource>
private final List<Resource>
private final List<String>
private static final Log
private Map<String, MediaType>
private boolean
private ResourceResolverChain
private ResourceHttpMessageWriter
private ResourceLoader
private final List<ResourceResolver>
private final List<ResourceTransformer>
private static final Set<HttpMethod>
private ResourceTransformerChain
private boolean

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public void
afterPropertiesSet()

Implements org.springframework.beans.factory.InitializingBean.afterPropertiesSet.

Invoked by the containing BeanFactory after it has set all bean properties and satisfied BeanFactoryAware, 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.

private String
private String
public CacheControl
getCacheControl()

Return the org.springframework.http.CacheControl instance to build the Cache-Control HTTP response header.

public Function<Resource, String>

Returns:

the HTTP ETag generator function
getEtagGenerator
()

Return the HTTP ETag generator function to be used when serving resources.

public List<Resource>
getLocations()

Return the List of Resource paths to use as sources for serving static resources.

public List<String>
getLocationValues()

Return the configured location values.

private MediaType
public Map<String, MediaType>
getMediaTypes()

Return the configured media type mappings.

protected Mono<Resource>
public ResourceHttpMessageWriter
getResourceHttpMessageWriter()

Return the configured resource message writer.

private String
public List<ResourceResolver>
getResourceResolvers()

Return the list of configured resource resolvers.

public List<ResourceTransformer>
getResourceTransformers()

Return the list of configured resource transformers.

public Mono<Void>
handle(ServerWebExchange
the current server exchange
exchange
)

Implements org.springframework.web.server.WebHandler.handle.

Processes a resource request.

protected void
initAllowedLocations()

Look for a PathResourceResolver among the configured resource resolvers and set its allowedLocations property (if empty) to match the locations configured on this class.

private boolean

Returns:

true if the path is invalid, false otherwise
isInvalidEncodedPath
(String
the path to validate
path
)

Check whether the given path contains invalid escape sequences.

protected boolean

Returns:

true if the path is invalid, false otherwise
isInvalidPath
(String
the path to validate
path
)

Identifies invalid resource paths.

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.

public boolean
isUseLastModified()

Return whether the Resource#lastModified() information is used to drive HTTP responses when serving static resources.

private String
protected String
processPath(String path)

Process the given resource path.

private void
public void
setCacheControl(CacheControl cacheControl)

Set the org.springframework.http.CacheControl instance to build the Cache-Control HTTP response header.

public void
setEtagGenerator(Function<Resource, String>
the HTTP ETag generator function to use.
etagGenerator
)

Configure a generator function that will be used to create the ETag information, given a Resource that is about to be written to the response.

protected void
setHeaders(ServerWebExchange
current exchange
exchange
,
Resource
the identified resource (never null)
resource
,
MediaType
the resource's media type (never null)
mediaType
)

Set headers on the response.

public void
setLocations(List<Resource> locations)

Set the List of Resource paths to use as sources for serving static resources.

public void
setLocationValues(List<String> locationValues)

Accepts a list of String-based location values to be resolved into Resource locations.

public void
setMediaTypes(Map<String, MediaType>
media type mappings
mediaTypes
)

Add mappings between file extensions extracted from the filename of static Resources and the media types to use for the response.

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.

public void
public void
setResourceLoader(ResourceLoader resourceLoader)

Provide the ResourceLoader to load location values with.

public void
setResourceResolvers(List<ResourceResolver> resourceResolvers)

Configure the list of ResourceResolvers to use.

public void
setResourceTransformers(List<ResourceTransformer> resourceTransformers)

Configure the list of ResourceTransformers to use.

public void
setUseLastModified(boolean useLastModified)

Set whether we should look at the Resource#lastModified() when serving resources and use this information to drive "Last-Modified" HTTP response headers.

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait

Field Detail

cacheControlback to summary
private CacheControl cacheControl
Annotations
@Nullable
etagGeneratorback to summary
private Function<Resource, String> etagGenerator
Annotations
@Nullable
locationResourcesback to summary
private final List<Resource> locationResources
locationsToUseback to summary
private final List<Resource> locationsToUse
locationValuesback to summary
private final List<String> locationValues
loggerback to summary
private static final Log logger
mediaTypesback to summary
private Map<String, MediaType> mediaTypes
Annotations
@Nullable
optimizeLocationsback to summary
private boolean optimizeLocations
resolverChainback to summary
private ResourceResolverChain resolverChain
Annotations
@Nullable
resourceHttpMessageWriterback to summary
private ResourceHttpMessageWriter resourceHttpMessageWriter
Annotations
@Nullable
resourceLoaderback to summary
private ResourceLoader resourceLoader
Annotations
@Nullable
resourceResolversback to summary
private final List<ResourceResolver> resourceResolvers
resourceTransformersback to summary
private final List<ResourceTransformer> resourceTransformers
SUPPORTED_METHODSback to summary
private static final Set<HttpMethod> SUPPORTED_METHODS
transformerChainback to summary
private ResourceTransformerChain transformerChain
Annotations
@Nullable
useLastModifiedback to summary
private boolean useLastModified

Constructor Detail

ResourceWebHandlerback to summary
public ResourceWebHandler()

Method Detail

afterPropertiesSetback to summary
public void afterPropertiesSet() throws Exception

Implements org.springframework.beans.factory.InitializingBean.afterPropertiesSet.

Doc from org.springframework.beans.factory.InitializingBean.afterPropertiesSet.

Invoked by the containing BeanFactory after it has set all bean properties and satisfied BeanFactoryAware, 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.

Annotations
@Override
Exceptions
Exception:
in the event of misconfiguration (such as failure to set an essential property) or if initialization fails for any other reason
cleanDuplicateSlashesback to summary
private String cleanDuplicateSlashes(String path)
cleanLeadingSlashback to summary
private String cleanLeadingSlash(String path)
getCacheControlback to summary
public CacheControl getCacheControl()

Return the org.springframework.http.CacheControl instance to build the Cache-Control HTTP response header.

Annotations
@Nullable
getEtagGeneratorback to summary
public Function<Resource, String> getEtagGenerator()

Return the HTTP ETag generator function to be used when serving resources.

Returns:Function<Resource, String>

the HTTP ETag generator function

Annotations
@Nullable
Since
6.1
getLocationsback to summary
public List<Resource> getLocations()

Return the List of Resource 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 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.

See Also
setLocationValues, setLocations
getLocationValuesback to summary
public List<String> getLocationValues()

Return the configured location values.

Since
5.1
getMediaTypeback to summary
private MediaType getMediaType(Resource resource)
Annotations
@Nullable
getMediaTypesback to summary
public Map<String, MediaType> getMediaTypes()

Return the configured media type mappings.

Since
5.3.2
getResourceback to summary
protected Mono<Resource> getResource(ServerWebExchange exchange)
getResourceHttpMessageWriterback to summary
public ResourceHttpMessageWriter getResourceHttpMessageWriter()

Return the configured resource message writer.

Annotations
@Nullable
getResourcePathback to summary
private String getResourcePath(ServerWebExchange exchange)
getResourceResolversback to summary
public List<ResourceResolver> getResourceResolvers()

Return the list of configured resource resolvers.

getResourceTransformersback to summary
public List<ResourceTransformer> getResourceTransformers()

Return the list of configured resource transformers.

handleback to summary
public Mono<Void> handle(ServerWebExchange exchange)

Implements org.springframework.web.server.WebHandler.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 the Last-Modified header, and its value will be compared against the last-modified timestamp of the given resource, returning a 304 status code if the Last-Modified value is greater. If the resource is newer than the Last-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.

Parameters
exchange:ServerWebExchange

Doc from org.springframework.web.server.WebHandler.handle.

the current server exchange

Returns:Mono<Void>

Doc from org.springframework.web.server.WebHandler.handle.

Mono<Void> to indicate when request handling is complete

Annotations
@Override
initAllowedLocationsback to summary
protected void initAllowedLocations()

Look for a PathResourceResolver among the configured resource resolvers and set its allowedLocations property (if empty) to match the locations configured on this class.

isInvalidEncodedPathback to summary
private boolean isInvalidEncodedPath(String path)

Check whether the given path contains invalid escape sequences.

Parameters
path:String

the path to validate

Returns:boolean

true if the path is invalid, false otherwise

isInvalidPathback to summary
protected boolean isInvalidPath(String path)

Identifies invalid resource paths. By default rejects:

  • Paths that contain "WEB-INF" or "META-INF"
  • Paths that contain "../" after a call to StringUtils#cleanPath.
  • 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:String

the path to validate

Returns:boolean

true if the path is invalid, false otherwise

isOptimizeLocationsback to summary
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
isUseLastModifiedback to summary
public boolean isUseLastModified()

Return whether the Resource#lastModified() information is used to drive HTTP responses when serving static resources.

Since
5.3
locationToStringback to summary
private String locationToString(List<Resource> locations)
processPathback to summary
protected String processPath(String path)

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".
resolveResourceLocationsback to summary
private void resolveResourceLocations()
setCacheControlback to summary
public void setCacheControl(CacheControl cacheControl)

Set the org.springframework.http.CacheControl instance to build the Cache-Control HTTP response header.

setEtagGeneratorback to summary
public void setEtagGenerator(Function<Resource, String> etagGenerator)

Configure a generator function that will be used to create the ETag information, given a Resource 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), or null if no value can be generated for the given resource.

Parameters
etagGenerator:Function<Resource, String>

the HTTP ETag generator function to use.

Since
6.1
setHeadersback to summary
protected void setHeaders(ServerWebExchange exchange, Resource resource, MediaType mediaType) throws IOException

Set headers on the response. Called for both GET and HEAD requests.

Parameters
exchange:ServerWebExchange

current exchange

resource:Resource

the identified resource (never null)

mediaType:MediaType

the resource's media type (never null)

setLocationsback to summary
public void setLocations(List<Resource> locations)

Set the List of Resource paths to use as sources for serving static resources.

setLocationValuesback to summary
public void setLocationValues(List<String> locationValues)

Accepts a list of String-based location values to be resolved into Resource locations.

Since
5.1
setMediaTypesback to summary
public void setMediaTypes(Map<String, MediaType> mediaTypes)

Add mappings between file extensions extracted from the filename of static Resources 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:Map<String, MediaType>

media type mappings

Since
5.3.2
setOptimizeLocationsback to summary
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 to true for optimized access in case of a consistent jar layout with directory entries.

Since
5.3.13
setResourceHttpMessageWriterback to summary
public void setResourceHttpMessageWriter(ResourceHttpMessageWriter httpMessageWriter)

Configure the ResourceHttpMessageWriter to use.

By default a ResourceHttpMessageWriter will be configured.

setResourceLoaderback to summary
public void setResourceLoader(ResourceLoader resourceLoader)

Provide the ResourceLoader to load location values with.

Since
5.1
setResourceResolversback to summary
public void setResourceResolvers(List<ResourceResolver> resourceResolvers)

Configure the list of ResourceResolvers to use.

By default PathResourceResolver is configured. If using this property, it is recommended to add PathResourceResolver as the last resolver.

setResourceTransformersback to summary
public void setResourceTransformers(List<ResourceTransformer> resourceTransformers)

Configure the list of ResourceTransformers to use.

By default no transformers are configured for use.

setUseLastModifiedback to summary
public void setUseLastModified(boolean useLastModified)

Set whether we should look at the Resource#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
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object. Satisfying this method's contract implies a non-null result must be returned.

Returns:String

a string representation of the object

Annotations
@Override