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, 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:
- 3.0.4
- Author:
- Keith Donald, Jeremy Grelle, Juergen Hoeller, Arjen Poutsma, Brian Clozel, Rossen Stoyanchev
-
Field Summary
Fields inherited from class WebContentGenerator
HEADER_CACHE_CONTROL, METHOD_GET, METHOD_HEAD, METHOD_POST -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidInvoked by the containingBeanFactoryafter it has set all bean properties and satisfiedBeanFactoryAware,ApplicationContextAwareetc.getCorsConfiguration(jakarta.servlet.http.HttpServletRequest request) Return the specified CORS configuration.Return the HTTP ETag generator function to be used when serving resources.Return the configuredListofResourcelocations including both String-based locations provided viasetLocationValuesand pre-resolvedResourcelocations provided viasetLocations.getMediaType(jakarta.servlet.http.HttpServletRequest request, Resource resource) Determine the media type for the given request and the resource matched to it.Return theconfiguredmedia types.getResource(jakarta.servlet.http.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.Deprecated, for removal: This API element is subject to removal in a future version.voidhandleRequest(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) Processes a resource request.protected voidLook for aPathResourceResolveramong the configured resource resolvers and set itsallowedLocationsproperty (if empty) to match thelocationsconfigured on this class.protected booleanisInvalidPath(String path) Invoked afterResourceHandlerUtils.isInvalidPath(String)to allow subclasses to perform further validation.booleanReturn 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.booleanReturn whether theResource.lastModified()information is used to drive HTTP responses when serving static resources.protected StringprocessPath(String path) Process the given resource path.voidsetCorsConfiguration(CorsConfiguration corsConfiguration) Specify the CORS configuration for resources served by this handler.voidsetEmbeddedValueResolver(StringValueResolver resolver) Set the StringValueResolver to use for resolving embedded definition values.voidsetEtagGenerator(@Nullable Function<Resource, String> etagGenerator) Configure a generator function that will be used to create the ETag information, given aResourcethat is about to be written to the response.protected voidsetHeaders(jakarta.servlet.http.HttpServletResponse response, Resource resource, @Nullable MediaType mediaType) Set headers on the given servlet response.voidsetLocations(List<Resource> locations) Configure locations to serve resources from as pre-resourced Resource's.voidsetLocationValues(List<String> locations) Configure String-based locations to serve resources from.voidsetMediaTypes(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.voidsetOptimizeLocations(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.voidsetResourceHttpMessageConverter(@Nullable ResourceHttpMessageConverter messageConverter) Configure theResourceHttpMessageConverterto use.voidsetResourceRegionHttpMessageConverter(@Nullable ResourceRegionHttpMessageConverter messageConverter) Configure theResourceRegionHttpMessageConverterto use.voidsetResourceResolvers(@Nullable List<ResourceResolver> resourceResolvers) Configure the list ofResourceResolversto use.voidsetResourceTransformers(@Nullable List<ResourceTransformer> resourceTransformers) Configure the list ofResourceTransformersto use.voidsetUrlPathHelper(@Nullable UrlPathHelper urlPathHelper) Deprecated, for removal: This API element is subject to removal in a future version.use ofPathMatcherandUrlPathHelperis deprecated for use at runtime in web modules in favor of parsed patterns withPathPatternParser.voidsetUseLastModified(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 WebContentGenerator
applyCacheControl, applyCacheSeconds, checkRequest, getAllowHeader, getCacheControl, getCacheSeconds, getSupportedMethods, getVaryByRequestHeaders, isRequireSession, prepareResponse, setCacheControl, setCacheSeconds, setRequireSession, setSupportedMethods, setVaryByRequestHeadersMethods inherited from class WebApplicationObjectSupport
getServletContext, getTempDir, getWebApplicationContext, initApplicationContext, initServletContext, isContextRequired, setServletContextMethods inherited from class 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(for example, 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
-
getLocations
Return the configuredListofResourcelocations including both String-based locations provided viasetLocationValuesand pre-resolvedResourcelocations provided viasetLocations.Note that the returned list is fully initialized only after initialization via
afterPropertiesSet().Note: 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).- See Also:
-
setResourceResolvers
Configure the list ofResourceResolversto use.By default
PathResourceResolveris configured. If using this property, it is recommended to addPathResourceResolveras the last resolver. -
getResourceResolvers
Return the list of configured resource resolvers. -
setResourceTransformers
Configure the list ofResourceTransformersto 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 theResourceHttpMessageConverterto use.By default a
ResourceHttpMessageConverterwill be configured.- Since:
- 4.3
-
getResourceHttpMessageConverter
Return the configured resource converter.- Since:
- 4.3
-
setResourceRegionHttpMessageConverter
public void setResourceRegionHttpMessageConverter(@Nullable ResourceRegionHttpMessageConverter messageConverter) Configure theResourceRegionHttpMessageConverterto use.By default a
ResourceRegionHttpMessageConverterwill be configured.- Since:
- 4.3
-
getResourceRegionHttpMessageConverter
Return the configured resource region converter.- 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
-
setCorsConfiguration
Specify the CORS configuration for resources served by this handler.By default this is not set in which allows cross-origin requests.
-
getCorsConfiguration
public @Nullable CorsConfiguration getCorsConfiguration(jakarta.servlet.http.HttpServletRequest request) Return the specified CORS configuration.- Specified by:
getCorsConfigurationin interfaceCorsConfigurationSource- Returns:
- the associated
CorsConfiguration, ornullif none
-
setUrlPathHelper
@Deprecated(since="7.0", forRemoval=true) public void setUrlPathHelper(@Nullable UrlPathHelper urlPathHelper) Deprecated, for removal: This API element is subject to removal in a future version.use ofPathMatcherandUrlPathHelperis deprecated for use at runtime in web modules in favor of parsed patterns withPathPatternParser.Provide a reference to theUrlPathHelperused 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
Deprecated, for removal: This API element is subject to removal in a future version.use ofPathMatcherandUrlPathHelperis deprecated for use at runtime in web modules in favor of parsed patterns withPathPatternParser.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
-
setEtagGenerator
Configure a generator function that will be used to create the ETag information, given aResourcethat 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), ornullif no value can be generated for the given resource.- Parameters:
etagGenerator- the HTTP ETag generator function to use.- Since:
- 6.1
-
getEtagGenerator
-
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 totruefor 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:EmbeddedValueResolverAwareSet the StringValueResolver to use for resolving embedded definition values.- Specified by:
setEmbeddedValueResolverin interfaceEmbeddedValueResolverAware
-
afterPropertiesSet
Description copied from interface:InitializingBeanInvoked by the containingBeanFactoryafter it has set all bean properties and satisfiedBeanFactoryAware,ApplicationContextAwareetc.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:
afterPropertiesSetin 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 aPathResourceResolveramong the configured resource resolvers and set itsallowedLocationsproperty (if empty) to match thelocationsconfigured on this class. -
handleRequest
public void handleRequest(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws jakarta.servlet.ServletException, IOException Processes a resource request.Finds the requested resource under one of the configured locations. If the resource does not exist,
NoResourceFoundExceptionis raised. If the resource exists, the request will be checked for the presence of theLast-Modifiedheader, and its value will be compared against the last-modified timestamp of the given resource, returning a304status code if theLast-Modifiedvalue is greater. If the resource is newer than theLast-Modifiedvalue, 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:
handleRequestin interfaceHttpRequestHandler- Parameters:
request- current HTTP requestresponse- current HTTP response- Throws:
jakarta.servlet.ServletException- in case of general errorsIOException- in case of I/O errors
-
getResource
protected @Nullable Resource getResource(jakarta.servlet.http.HttpServletRequest request) throws IOException - Throws:
IOException
-
processPath
Process the given resource path.By default, this method delegates to
ResourceHandlerUtils.normalizeInputPath(String).- Since:
- 3.2.12
-
isInvalidPath
Invoked afterResourceHandlerUtils.isInvalidPath(String)to allow subclasses to perform further validation.By default, this method does not perform any validations.
-
getMediaType
protected @Nullable MediaType getMediaType(jakarta.servlet.http.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:ServletContext.getMimeType(String)getMediaTypes()MediaTypeFactory.getMediaType(String)
- Parameters:
request- the current requestresource- the resource to check- Returns:
- the corresponding media type, or
nullif none found
-
setHeaders
protected void setHeaders(jakarta.servlet.http.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- Throws:
IOException- in case of errors while setting the headers
-
toString
-
PathMatcherandUrlPathHelperis deprecated for use at runtime in web modules in favor of parsed patterns withPathPatternParser.