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

public Class ResourceHttpRequestHandler

extends WebContentGenerator
implements HttpRequestHandler, EmbeddedValueResolverAware, InitializingBean, CorsConfigurationSource
Class Inheritance
All Implemented Interfaces
org.springframework.web.cors.CorsConfigurationSource, org.springframework.beans.factory.InitializingBean, org.springframework.context.EmbeddedValueResolverAware, org.springframework.beans.factory.Aware, org.springframework.web.HttpRequestHandler
Imports
java.io.IOException, java.net.URLDecoder, java.nio.charset.Charset, .StandardCharsets, java.util.ArrayList, .HashMap, .List, .Locale, .Map, java.util.function.Function, jakarta.servlet.ServletException, jakarta.servlet.http.HttpServletRequest, .HttpServletResponse, org.apache.commons.logging.Log, .LogFactory, org.springframework.beans.factory.InitializingBean, org.springframework.context.ApplicationContext, .EmbeddedValueResolverAware, org.springframework.core.io.Resource, .UrlResource, org.springframework.core.log.LogFormatUtils, org.springframework.http.HttpHeaders, .HttpMethod, .HttpRange, .MediaType, .MediaTypeFactory, org.springframework.http.converter.ResourceHttpMessageConverter, .ResourceRegionHttpMessageConverter, org.springframework.http.server.ServletServerHttpRequest, .ServletServerHttpResponse, org.springframework.lang.Nullable, org.springframework.util.Assert, .CollectionUtils, .ObjectUtils, .ResourceUtils, .StringUtils, .StringValueResolver, org.springframework.web.HttpRequestHandler, org.springframework.web.accept.ContentNegotiationManager, org.springframework.web.context.request.ServletWebRequest, org.springframework.web.context.support.ServletContextResource, org.springframework.web.cors.CorsConfiguration, .CorsConfigurationSource, org.springframework.web.servlet.HandlerMapping, org.springframework.web.servlet.support.WebContentGenerator, org.springframework.web.util.UrlPathHelper

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.

Authors
Keith Donald, Jeremy Grelle, Juergen Hoeller, Arjen Poutsma, Brian Clozel, Rossen Stoyanchev
Since
3.0.4

Field Summary

Modifier and TypeField and Description
private ContentNegotiationManager
private CorsConfiguration
private StringValueResolver
private Function<Resource, String>
private final Map<Resource, Charset>
private final List<Resource>
private final List<Resource>
private final List<String>
private static final Log
private final Map<String, MediaType>
private boolean
private ResourceResolverChain
private ResourceHttpMessageConverter
private ResourceRegionHttpMessageConverter
private final List<ResourceResolver>
private final List<ResourceTransformer>
private ResourceTransformerChain
private static final String
private UrlPathHelper
private boolean
Inherited from org.springframework.web.servlet.support.WebContentGenerator:
HEADER_CACHE_CONTROLMETHOD_GETMETHOD_HEADMETHOD_POST

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 ContentNegotiationManager
getContentNegotiationManager()
Deprecated as of 5.2.4

Return the configured content negotiation manager.

public CorsConfiguration
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 configured List of Resource locations including both String-based locations provided via setLocationValues and pre-resolved Resource locations provided via setLocations.

protected MediaType

Returns:

the corresponding media type, or null if none found
getMediaType
(HttpServletRequest
the current request
request
,
Resource
the resource to check
resource
)

Determine the media type for the given request and the resource matched to it.

public Map<String, MediaType>
getMediaTypes()

Return the configured media types.

private static String
protected Resource
public ResourceHttpMessageConverter
getResourceHttpMessageConverter()

Return the configured resource converter.

public ResourceRegionHttpMessageConverter
getResourceRegionHttpMessageConverter()

Return the configured resource region converter.

public List<ResourceResolver>
getResourceResolvers()

Return the list of configured resource resolvers.

public List<ResourceTransformer>
getResourceTransformers()

Return the list of configured resource transformers.

public UrlPathHelper
public void
handleRequest(HttpServletRequest
current HTTP request
request
,
HttpServletResponse
current HTTP response
response
)

Implements org.springframework.web.HttpRequestHandler.handleRequest.

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.

protected PathExtensionContentNegotiationStrategy
initContentNegotiationStrategy()
Deprecated as of 5.2.4 this method returns null, and if a subclass returns an actual instance, the instance is used only as a source of media type mappings, if it contains any.

Initialize the strategy to use to determine the media type for a resource.

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
setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager)
Deprecated as of 5.2.4 in favor of using setMediaTypes(Map) with mappings possibly obtained from ContentNegotiationManager#getMediaTypeMappings().

Configure a ContentNegotiationManager to help determine the media types for resources being served.

public void
setCorsConfiguration(CorsConfiguration corsConfiguration)

Specify the CORS configuration for resources served by this handler.

public void
setEmbeddedValueResolver(StringValueResolver resolver)

Implements org.springframework.context.EmbeddedValueResolverAware.setEmbeddedValueResolver.

Set the StringValueResolver to use for resolving embedded definition values.

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(HttpServletResponse
current servlet response
response
,
Resource
the identified resource (never null)
resource
,
MediaType
the resource's media type (never null)
mediaType
)

Set headers on the given servlet response.

public void
setLocations(List<Resource> locations)

Configure locations to serve resources from as pre-resourced Resource's.

public void
setLocationValues(List<String> locations)

Configure String-based locations to serve resources from.

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

Add mappings between file extensions, extracted from the filename of a static Resource, and corresponding media type to set on 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
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
setUrlPathHelper(UrlPathHelper urlPathHelper)

Provide a reference to the UrlPathHelper used to map requests to static resources.

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 org.springframework.web.servlet.support.WebContentGenerator:
applyCacheControlapplyCacheSecondsapplyCacheSecondscacheForSecondscacheForSecondscheckAndPreparecheckRequestgetAllowHeadergetCacheControlgetCacheSecondsgetSupportedMethodsgetVaryByRequestHeadersisAlwaysMustRevalidateisRequireSessionisUseCacheControlHeaderisUseCacheControlNoStoreisUseExpiresHeaderprepareResponsepreventCachingsetAlwaysMustRevalidatesetCacheControlsetCacheSecondssetRequireSessionsetSupportedMethodssetUseCacheControlHeadersetUseCacheControlNoStoresetUseExpiresHeadersetVaryByRequestHeaders

Field Detail

contentNegotiationManagerback to summary
private ContentNegotiationManager contentNegotiationManager
Annotations
@Nullable
corsConfigurationback to summary
private CorsConfiguration corsConfiguration
Annotations
@Nullable
embeddedValueResolverback to summary
private StringValueResolver embeddedValueResolver
Annotations
@Nullable
etagGeneratorback to summary
private Function<Resource, String> etagGenerator
Annotations
@Nullable
locationCharsetsback to summary
private final Map<Resource, Charset> locationCharsets
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

Hides org.springframework.context.support.ApplicationObjectSupport.logger.

mediaTypesback to summary
private final Map<String, MediaType> mediaTypes
optimizeLocationsback to summary
private boolean optimizeLocations
resolverChainback to summary
private ResourceResolverChain resolverChain
Annotations
@Nullable
resourceHttpMessageConverterback to summary
private ResourceHttpMessageConverter resourceHttpMessageConverter
Annotations
@Nullable
resourceRegionHttpMessageConverterback to summary
private ResourceRegionHttpMessageConverter resourceRegionHttpMessageConverter
Annotations
@Nullable
resourceResolversback to summary
private final List<ResourceResolver> resourceResolvers
resourceTransformersback to summary
private final List<ResourceTransformer> resourceTransformers
transformerChainback to summary
private ResourceTransformerChain transformerChain
Annotations
@Nullable
URL_RESOURCE_CHARSET_PREFIXback to summary
private static final String URL_RESOURCE_CHARSET_PREFIX
urlPathHelperback to summary
private UrlPathHelper urlPathHelper
Annotations
@Nullable
useLastModifiedback to summary
private boolean useLastModified

Constructor Detail

ResourceHttpRequestHandlerback to summary
public ResourceHttpRequestHandler()

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)
getContentNegotiationManagerback to summary
public ContentNegotiationManager getContentNegotiationManager()

Deprecated

as of 5.2.4

Return the configured content negotiation manager.

Annotations
@Nullable
@Deprecated
Since
4.3
getCorsConfigurationback to summary
public CorsConfiguration getCorsConfiguration(HttpServletRequest request)

Implements org.springframework.web.cors.CorsConfigurationSource.getCorsConfiguration.

Return the specified CORS configuration.

Returns:CorsConfiguration

Doc from org.springframework.web.cors.CorsConfigurationSource.getCorsConfiguration.

the associated CorsConfiguration, or null if none

Annotations
@Override
@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 configured List of Resource locations including both String-based locations provided via setLocationValues and pre-resolved Resource locations provided via setLocations.

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.

See Also
setLocationValues, setLocations
getMediaTypeback to summary
protected MediaType getMediaType(HttpServletRequest request, Resource resource)

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:

  1. jakarta.servlet.ServletContext#getMimeType(String)
  2. getMediaTypes()
  3. MediaTypeFactory#getMediaType(String)
Parameters
request:HttpServletRequest

the current request

resource:Resource

the resource to check

Returns:MediaType

the corresponding media type, or null if none found

Annotations
@Nullable
getMediaTypesback to summary
public Map<String, MediaType> getMediaTypes()

Return the configured media types.

Since
5.2.4
getPathback to summary
private static String getPath(HttpServletRequest request)
getResourceback to summary
protected Resource getResource(HttpServletRequest request) throws IOException
Annotations
@Nullable
getResourceHttpMessageConverterback to summary
public ResourceHttpMessageConverter getResourceHttpMessageConverter()

Return the configured resource converter.

Annotations
@Nullable
Since
4.3
getResourceRegionHttpMessageConverterback to summary
public ResourceRegionHttpMessageConverter getResourceRegionHttpMessageConverter()

Return the configured resource region converter.

Annotations
@Nullable
Since
4.3
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.

getUrlPathHelperback to summary
public UrlPathHelper getUrlPathHelper()

The configured UrlPathHelper.

Annotations
@Nullable
Since
4.3.13
handleRequestback to summary
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

Implements org.springframework.web.HttpRequestHandler.handleRequest.

Processes a resource request.

Finds the requested resource under one of the configured locations. If the resource does not exist, NoResourceFoundException is raised. 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
request:HttpServletRequest

Doc from org.springframework.web.HttpRequestHandler.handleRequest.

current HTTP request

response:HttpServletResponse

Doc from org.springframework.web.HttpRequestHandler.handleRequest.

current HTTP response

Annotations
@Override
Exceptions
ServletException:

Doc from org.springframework.web.HttpRequestHandler.handleRequest.

in case of general errors

IOException:

Doc from org.springframework.web.HttpRequestHandler.handleRequest.

in case of I/O errors

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.

initContentNegotiationStrategyback to summary
protected PathExtensionContentNegotiationStrategy initContentNegotiationStrategy()

Deprecated

as of 5.2.4 this method returns null, 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, use setMediaTypes(Map) instead, or if you need to change behavior, you can override getMediaType(HttpServletRequest, Resource).

Initialize the strategy to use to determine the media type for a resource.

Annotations
@Nullable
@Deprecated
@SuppressWarnings:deprecation
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:

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

Since
3.0.6
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".
Since
3.2.12
resolveResourceLocationsback to summary
private void resolveResourceLocations()
setContentNegotiationManagerback to summary
public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager)

Deprecated

as of 5.2.4 in favor of using setMediaTypes(Map) with mappings possibly obtained from ContentNegotiationManager#getMediaTypeMappings().

Configure a ContentNegotiationManager 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.

Annotations
@Deprecated
Since
4.3
setCorsConfigurationback to summary
public void setCorsConfiguration(CorsConfiguration corsConfiguration)

Specify the CORS configuration for resources served by this handler.

By default this is not set in which allows cross-origin requests.

setEmbeddedValueResolverback to summary
public void setEmbeddedValueResolver(StringValueResolver resolver)

Implements org.springframework.context.EmbeddedValueResolverAware.setEmbeddedValueResolver.

Doc from org.springframework.context.EmbeddedValueResolverAware.setEmbeddedValueResolver.

Set the StringValueResolver to use for resolving embedded definition values.

Annotations
@Override
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 ServletWebRequest#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(HttpServletResponse response, Resource resource, MediaType mediaType) throws IOException

Set headers on the given servlet response. Called for GET requests as well as HEAD requests.

Parameters
response:HttpServletResponse

current servlet response

resource:Resource

the identified resource (never null)

mediaType:MediaType

the resource's media type (never null)

Exceptions
IOException:
in case of errors while setting the headers
setLocationsback to summary
public void setLocations(List<Resource> locations)

Configure locations to serve resources from as pre-resourced Resource's.

See Also
setLocationValues(List)
setLocationValuesback to summary
public void setLocationValues(List<String> locations)

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(List)
setMediaTypesback to summary
public void setMediaTypes(Map<String, MediaType> mediaTypes)

Add mappings between file extensions, extracted from the filename of a static Resource, and corresponding media type to set on the response.

Use of this method is typically not necessary since mappings are otherwise determined via jakarta.servlet.ServletContext#getMimeType(String) or via MediaTypeFactory#getMediaType(Resource).

Parameters
mediaTypes:Map<String, MediaType>

media type mappings

Since
5.2.4
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
setResourceHttpMessageConverterback to summary
public void setResourceHttpMessageConverter(ResourceHttpMessageConverter messageConverter)

Configure the ResourceHttpMessageConverter to use.

By default a ResourceHttpMessageConverter will be configured.

Since
4.3
setResourceRegionHttpMessageConverterback to summary
public void setResourceRegionHttpMessageConverter(ResourceRegionHttpMessageConverter messageConverter)

Configure the ResourceRegionHttpMessageConverter to use.

By default a ResourceRegionHttpMessageConverter will be configured.

Since
4.3
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.

setUrlPathHelperback to summary
public void setUrlPathHelper(UrlPathHelper urlPathHelper)

Provide a reference to the UrlPathHelper 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
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