Package org.springframework.web.servlet.resource

# Class ResourceHttpRequestHandler

java.lang.Object
org.springframework.context.support.ApplicationObjectSupport
org.springframework.web.context.support.WebApplicationObjectSupport
org.springframework.web.servlet.support.WebContentGenerator
org.springframework.web.servlet.resource.ResourceHttpRequestHandler

All Implemented Interfaces:
  `org.springframework.beans.factory.Aware`, `org.springframework.beans.factory.InitializingBean`, `org.springframework.context.ApplicationContextAware`, `org.springframework.context.EmbeddedValueResolverAware`, `org.springframework.web.context.ServletContextAware`, `org.springframework.web.cors.CorsConfigurationSource`, `org.springframework.web.HttpRequestHandler`

public class ResourceHttpRequestHandler extends WebContentGenerator implements org.springframework.web.HttpRequestHandler, org.springframework.context.EmbeddedValueResolverAware, org.springframework.beans.factory.InitializingBean, org.springframework.web.cors.CorsConfigurationSource
`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 org.springframework.web.servlet.support.WebContentGenerator

`HEADER_CACHE_CONTROL, METHOD_GET, METHOD_HEAD, METHOD_POST`

## Constructor Summary

Constructors
Constructor
Description
`ResourceHttpRequestHandler()`

## Method Summary

Modifier and Type
Method
Description
`void`
`afterPropertiesSet()`
`org.springframework.web.accept.ContentNegotiationManager`
`getContentNegotiationManager()`
Deprecated.
as of 5.2.4
`org.springframework.web.cors.CorsConfiguration`
`getCorsConfiguration(HttpServletRequest request)`
Return the specified CORS configuration.
`Function<org.springframework.core.io.Resource,String>`
`getEtagGenerator()`
Return the HTTP ETag generator function to be used when serving resources.
`List<org.springframework.core.io.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 org.springframework.http.MediaType`
`getMediaType(HttpServletRequest request, org.springframework.core.io.Resource resource)`
Determine the media type for the given request and the resource matched to it.
`Map<String,org.springframework.http.MediaType>`
`getMediaTypes()`
Return the `configured` media types.
`protected org.springframework.core.io.Resource`
`getResource(HttpServletRequest request)`
`org.springframework.http.converter.ResourceHttpMessageConverter`
`getResourceHttpMessageConverter()`
Return the configured resource converter.
`org.springframework.http.converter.ResourceRegionHttpMessageConverter`
`getResourceRegionHttpMessageConverter()`
Return the configured resource region converter.
`List<ResourceResolver>`
`getResourceResolvers()`
Return the list of configured resource resolvers.
`List<ResourceTransformer>`
`getResourceTransformers()`
Return the list of configured resource transformers.
`org.springframework.web.util.UrlPathHelper`
`getUrlPathHelper()`
The configured `UrlPathHelper`.
`void`
`handleRequest(HttpServletRequest request, HttpServletResponse response)`
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 org.springframework.web.accept.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.
`protected boolean`
`isInvalidPath(String path)`
Invoked after `ResourceHandlerUtils.isInvalidPath(String)` to allow subclasses to perform further validation.
`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.
`boolean`
`isUseLastModified()`
Return whether the `Resource.lastModified()` information is used to drive HTTP responses when serving static resources.
`protected String`
`processPath(String path)`
Process the given resource path.
`void`
`setContentNegotiationManager(org.springframework.web.accept.ContentNegotiationManager contentNegotiationManager)`
Deprecated.
as of 5.2.4 in favor of using `setMediaTypes(Map)` with mappings possibly obtained from `ContentNegotiationManager.getMediaTypeMappings()`.
`void`
`setCorsConfiguration(org.springframework.web.cors.CorsConfiguration corsConfiguration)`
Specify the CORS configuration for resources served by this handler.
`void`
`setEmbeddedValueResolver(org.springframework.util.StringValueResolver resolver)`
`void`
`setEtagGenerator(Function<org.springframework.core.io.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.
`protected void`
`setHeaders(HttpServletResponse response, org.springframework.core.io.Resource resource, org.springframework.http.MediaType mediaType)`
Set headers on the given servlet response.
`void`
`setLocations(List<org.springframework.core.io.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,org.springframework.http.MediaType> mediaTypes)`
Add mappings between file extensions, extracted from the filename of a static `Resource`, 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(org.springframework.http.converter.ResourceHttpMessageConverter messageConverter)`
Configure the `ResourceHttpMessageConverter` to use.
`void`
`setResourceRegionHttpMessageConverter(org.springframework.http.converter.ResourceRegionHttpMessageConverter messageConverter)`
Configure the `ResourceRegionHttpMessageConverter` to use.
`void`
`setResourceResolvers(List<ResourceResolver> resourceResolvers)`
Configure the list of `ResourceResolvers` to use.
`void`
`setResourceTransformers(List<ResourceTransformer> resourceTransformers)`
Configure the list of `ResourceTransformers` to use.
`void`
`setUrlPathHelper(org.springframework.web.util.UrlPathHelper urlPathHelper)`
Provide a reference to the `UrlPathHelper` used to map requests to static resources.
`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.
`String`
`toString()`

### Methods inherited from class org.springframework.web.servlet.support.WebContentGenerator

`applyCacheControl, applyCacheSeconds, checkAndPrepare, checkRequest, getAllowHeader, getCacheControl, getCacheSeconds, getSupportedMethods, getVaryByRequestHeaders, isRequireSession, prepareResponse, setCacheControl, setCacheSeconds, setRequireSession, setSupportedMethods, 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`

### Methods inherited from class java.lang.Object

`clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

## Constructor Details

### ResourceHttpRequestHandler

public ResourceHttpRequestHandler()

## Method Details

### setLocationValues

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` (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(List)`

### setLocations

public void setLocations(List<org.springframework.core.io.Resource> locations)
Configure locations to serve resources from as pre-resourced Resource's.

See Also:
  - `setLocationValues(List)`

### getLocations

public List<org.springframework.core.io.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: 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:
  - `setLocationValues(java.util.List<java.lang.String>)`
  - `setLocations(java.util.List<org.springframework.core.io.Resource>)`

### setResourceResolvers

public void setResourceResolvers(@Nullable 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.

### getResourceResolvers

public List<ResourceResolver> getResourceResolvers()
Return the list of configured resource resolvers.

### setResourceTransformers

public void setResourceTransformers(@Nullable List<ResourceTransformer> resourceTransformers)
Configure the list of `ResourceTransformers` to use.

By default no transformers are configured for use.

### getResourceTransformers

public List<ResourceTransformer> getResourceTransformers()
Return the list of configured resource transformers.

### setResourceHttpMessageConverter

public void setResourceHttpMessageConverter(@Nullable org.springframework.http.converter.ResourceHttpMessageConverter messageConverter)
Configure the `ResourceHttpMessageConverter` to use.

By default a `ResourceHttpMessageConverter` will be configured.

Since:
  4.3

### getResourceHttpMessageConverter

@Nullable public org.springframework.http.converter.ResourceHttpMessageConverter getResourceHttpMessageConverter()
Return the configured resource converter.

Since:
  4.3

### setResourceRegionHttpMessageConverter

public void setResourceRegionHttpMessageConverter(@Nullable org.springframework.http.converter.ResourceRegionHttpMessageConverter messageConverter)
Configure the `ResourceRegionHttpMessageConverter` to use.

By default a `ResourceRegionHttpMessageConverter` will be configured.

Since:
  4.3

### getResourceRegionHttpMessageConverter

@Nullable public org.springframework.http.converter.ResourceRegionHttpMessageConverter getResourceRegionHttpMessageConverter()
Return the configured resource region converter.

Since:
  4.3

### setContentNegotiationManager

@Deprecated public void setContentNegotiationManager(@Nullable org.springframework.web.accept.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.

Since:
  4.3

### getContentNegotiationManager

@Nullable @Deprecated public org.springframework.web.accept.ContentNegotiationManager getContentNegotiationManager()
Deprecated.
as of 5.2.4
Return the configured content negotiation manager.

Since:
  4.3

### setMediaTypes

public void setMediaTypes(Map<String,org.springframework.http.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 `ServletContext.getMimeType(String)` or via `MediaTypeFactory.getMediaType(Resource)`.

Parameters:
  `mediaTypes` - media type mappings
Since:
  5.2.4

### getMediaTypes

public Map<String,org.springframework.http.MediaType> getMediaTypes()
Return the `configured` media types.

Since:
  5.2.4

### setCorsConfiguration

public void setCorsConfiguration(org.springframework.web.cors.CorsConfiguration corsConfiguration)
Specify the CORS configuration for resources served by this handler.

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

### getCorsConfiguration

@Nullable public org.springframework.web.cors.CorsConfiguration getCorsConfiguration(HttpServletRequest request)
Return the specified CORS configuration.

Specified by:
  `getCorsConfiguration` in interface `org.springframework.web.cors.CorsConfigurationSource`

### setUrlPathHelper

public void setUrlPathHelper(@Nullable org.springframework.web.util.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

### getUrlPathHelper

@Nullable public org.springframework.web.util.UrlPathHelper getUrlPathHelper()
The configured `UrlPathHelper`.

Since:
  4.3.13

### setUseLastModified

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

### isUseLastModified

public boolean isUseLastModified()
Return whether the `Resource.lastModified()` information is used to drive HTTP responses when serving static resources.

Since:
  5.3

### setEtagGenerator

public void setEtagGenerator(@Nullable Function<org.springframework.core.io.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` - the HTTP ETag generator function to use.
Since:
  6.1

### getEtagGenerator

@Nullable public Function<org.springframework.core.io.Resource,String> 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 to `true` 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

public void setEmbeddedValueResolver(org.springframework.util.StringValueResolver resolver)

Specified by:
  `setEmbeddedValueResolver` in interface `org.springframework.context.EmbeddedValueResolverAware`

### afterPropertiesSet

public void afterPropertiesSet() throws Exception

Specified by:
  `afterPropertiesSet` in interface `org.springframework.beans.factory.InitializingBean`
Throws:
  `Exception`

### initAllowedLocations

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.

### initContentNegotiationStrategy

@Nullable @Deprecated protected org.springframework.web.accept.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.

### handleRequest

public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
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.

Specified by:
  `handleRequest` in interface `org.springframework.web.HttpRequestHandler`
Throws:
  `ServletException`
  `IOException`

### getResource

@Nullable protected org.springframework.core.io.Resource getResource(HttpServletRequest request) throws IOException

Throws:
  `IOException`

### processPath

protected String processPath(String path)
Process the given resource path.

By default, this method delegates to `ResourceHandlerUtils.normalizeInputPath(java.lang.String)`.

Since:
  3.2.12

### isInvalidPath

protected boolean isInvalidPath(String path)
Invoked after `ResourceHandlerUtils.isInvalidPath(String)` to allow subclasses to perform further validation.

By default, this method does not perform any validations.

### getMediaType

@Nullable protected org.springframework.http.MediaType getMediaType(HttpServletRequest request, org.springframework.core.io.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. `ServletContext.getMimeType(String)`
2. `getMediaTypes()`
3. `MediaTypeFactory.getMediaType(String)`

Parameters:
  `request` - the current request
  `resource` - the resource to check
Returns:
  the corresponding media type, or `null` if none found

### setHeaders

protected void setHeaders(HttpServletResponse response, org.springframework.core.io.Resource resource, @Nullable org.springframework.http.MediaType mediaType) throws IOException
Set headers on the given servlet response. Called for GET requests as well as HEAD requests.

Parameters:
  `response` - current servlet response
  `resource` - the identified resource (never `null`)
  `mediaType` - the resource's media type
Throws:
  `IOException` - in case of errors while setting the headers

### toString

public String toString()

Overrides:
  `toString` in class `Object`