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:
Aware,InitializingBean,ApplicationContextAware,EmbeddedValueResolverAware,ServletContextAware,CorsConfigurationSource,HttpRequestHandler
public class ResourceHttpRequestHandler extends WebContentGenerator implements HttpRequestHandler, EmbeddedValueResolverAware, InitializingBean, CorsConfigurationSource
HttpRequestHandlerthat serves static resources in an optimized way according to the guidelines of Page Speed, YSlow, etc.The "locations" property takes a list of Spring
Resourcelocations 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
resourcesResolverandresourceTransformerchains to support arbitrary resolution and transformation of resources being served. By default aPathResourceResolversimply finds resources based on the configured "locations". An application can configure additional resolvers and transformers such as theVersionResourceResolverwhich can resolve and prepare URLs for resources with a version in the URL.This handler also properly evaluates the
Last-Modifiedheader (if present) so that a304status 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
All Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidafterPropertiesSet()Invoked by the containingBeanFactoryafter it has set all bean properties and satisfiedBeanFactoryAware,ApplicationContextAwareetc.ContentNegotiationManagergetContentNegotiationManager()Return the configured content negotiation manager.CorsConfigurationgetCorsConfiguration(HttpServletRequest request)Return the specified CORS configuration.List<Resource>getLocations()Return the configuredListofResourcelocations.protected MediaTypegetMediaType(HttpServletRequest request, Resource resource)Determine the media type for the given request and the resource matched to it.protected MediaTypegetMediaType(Resource resource)Deprecated.as of 4.3 this method is deprecated; please overridegetMediaType(HttpServletRequest, Resource)instead.protected ResourcegetResource(HttpServletRequest request)ResourceHttpMessageConvertergetResourceHttpMessageConverter()Return the configured resource converter.ResourceRegionHttpMessageConvertergetResourceRegionHttpMessageConverter()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.UrlPathHelpergetUrlPathHelper()The configuredUrlPathHelper.voidhandleRequest(HttpServletRequest request, HttpServletResponse response)Processes a resource request.protected voidinitAllowedLocations()Look for aPathResourceResolveramong the configured resource resolvers and set itsallowedLocationsproperty (if empty) to match thelocationsconfigured on this class.protected PathExtensionContentNegotiationStrategyinitContentNegotiationStrategy()Initialize the content negotiation strategy depending on theContentNegotiationManagersetup and the availability of aServletContext.protected booleanisInvalidPath(String path)Identifies invalid resource paths.protected StringprocessPath(String path)Process the given resource path.voidsetContentNegotiationManager(ContentNegotiationManager contentNegotiationManager)Configure aContentNegotiationManagerto help determine the media types for resources being served.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.protected voidsetHeaders(HttpServletResponse response, Resource resource, MediaType mediaType)Set headers on the given servlet response.voidsetLocations(List<Resource> locations)Set theListofResourcelocations to use as sources for serving static resources.voidsetLocationValues(List<String> locationValues)An alternative tosetLocations(List)that accepts a list of String-based location values, with support forUrlResource's (e.g.voidsetResourceHttpMessageConverter(ResourceHttpMessageConverter messageConverter)Configure theResourceHttpMessageConverterto use.voidsetResourceRegionHttpMessageConverter(ResourceRegionHttpMessageConverter messageConverter)Configure theResourceRegionHttpMessageConverterto use.voidsetResourceResolvers(List<ResourceResolver> resourceResolvers)Configure the list ofResourceResolvers to use.voidsetResourceTransformers(List<ResourceTransformer> resourceTransformers)Configure the list ofResourceTransformers to use.voidsetUrlPathHelper(UrlPathHelper urlPathHelper)Provide a reference to theUrlPathHelperused to map requests to static resources.StringtoString()Methods inherited from class org.springframework.web.servlet.support.WebContentGenerator
applyCacheControl, applyCacheSeconds, applyCacheSeconds, cacheForSeconds, cacheForSeconds, checkAndPrepare, checkAndPrepare, checkRequest, getAllowHeader, getCacheControl, getCacheSeconds, getSupportedMethods, getVaryByRequestHeaders, isAlwaysMustRevalidate, isRequireSession, isUseCacheControlHeader, isUseCacheControlNoStore, isUseExpiresHeader, prepareResponse, preventCaching, setAlwaysMustRevalidate, setCacheControl, setCacheSeconds, setRequireSession, setSupportedMethods, setUseCacheControlHeader, setUseCacheControlNoStore, setUseExpiresHeader, 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, requiredContextClass, setApplicationContext
Constructor Detail
ResourceHttpRequestHandler
public ResourceHttpRequestHandler()
Method Detail
setLocationValues
public void setLocationValues(List<String> locationValues)
An alternative tosetLocations(List)that accepts a list of String-based location values, with support forUrlResource's (e.g. files or HTTP URLs) with a special prefix to indicate the charset to use when appending relative paths. For example"[charset=Windows-31J]https://example.org/path".- Since:
- 4.3.13
setLocations
public void setLocations(List<Resource> locations)
Set theListofResourcelocations to use as sources for serving static resources.- See Also:
setLocationValues(List)
getLocations
public List<Resource> getLocations()
Return the configuredListofResourcelocations.Note that if
locationValuesare provided, instead of loaded Resource-based locations, this method will return empty until after initialization viaafterPropertiesSet().
setResourceResolvers
public void setResourceResolvers(List<ResourceResolver> resourceResolvers)
Configure the list ofResourceResolvers to use.By default
PathResourceResolveris configured. If using this property, it is recommended to addPathResourceResolveras the last resolver.
getResourceResolvers
public List<ResourceResolver> getResourceResolvers()
Return the list of configured resource resolvers.
setResourceTransformers
public void setResourceTransformers(List<ResourceTransformer> resourceTransformers)
Configure the list ofResourceTransformers 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(ResourceHttpMessageConverter messageConverter)
Configure theResourceHttpMessageConverterto use.By default a
ResourceHttpMessageConverterwill be configured.- Since:
- 4.3
getResourceHttpMessageConverter
public ResourceHttpMessageConverter getResourceHttpMessageConverter()
Return the configured resource converter.- Since:
- 4.3
setResourceRegionHttpMessageConverter
public void setResourceRegionHttpMessageConverter(ResourceRegionHttpMessageConverter messageConverter)
Configure theResourceRegionHttpMessageConverterto use.By default a
ResourceRegionHttpMessageConverterwill be configured.- Since:
- 4.3
getResourceRegionHttpMessageConverter
public ResourceRegionHttpMessageConverter getResourceRegionHttpMessageConverter()
Return the configured resource region converter.- Since:
- 4.3
setContentNegotiationManager
public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager)
Configure aContentNegotiationManagerto 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
public ContentNegotiationManager getContentNegotiationManager()
Return the configured content negotiation manager.- Since:
- 4.3
setCorsConfiguration
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.
getCorsConfiguration
public CorsConfiguration getCorsConfiguration(HttpServletRequest request)
Return the specified CORS configuration.- Specified by:
getCorsConfigurationin interfaceCorsConfigurationSource- Returns:
- the associated
CorsConfiguration, ornullif none
setUrlPathHelper
public void setUrlPathHelper(UrlPathHelper urlPathHelper)
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
public UrlPathHelper getUrlPathHelper()
The configuredUrlPathHelper.- Since:
- 4.3.13
setEmbeddedValueResolver
public void setEmbeddedValueResolver(StringValueResolver resolver)
Description copied from interface:EmbeddedValueResolverAwareSet the StringValueResolver to use for resolving embedded definition values.- Specified by:
setEmbeddedValueResolverin interfaceEmbeddedValueResolverAware
afterPropertiesSet
public void afterPropertiesSet() throws Exception
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.
initContentNegotiationStrategy
protected PathExtensionContentNegotiationStrategy initContentNegotiationStrategy()
Initialize the content negotiation strategy depending on theContentNegotiationManagersetup and the availability of aServletContext.
handleRequest
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
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
404response will be returned to the client. 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:
ServletException- in case of general errorsIOException- in case of I/O errors
getResource
protected Resource getResource(HttpServletRequest request) throws IOException
- Throws:
IOException
processPath
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
isInvalidPath
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(java.lang.String). - Paths that represent a
valid URLor 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- the path to validate- Returns:
trueif the path is invalid,falseotherwise- Since:
- 3.0.6
getMediaType
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 based on the file extension of the Resource viaServletPathExtensionContentNegotiationStrategy.getMediaTypeForResource(org.springframework.core.io.Resource).- Parameters:
request- the current requestresource- the resource to check- Returns:
- the corresponding media type, or
nullif none found
getMediaType
@Deprecated protected MediaType getMediaType(Resource resource)
Deprecated.as of 4.3 this method is deprecated; please overridegetMediaType(HttpServletRequest, Resource)instead.Determine an appropriate media type for the given resource.- Parameters:
resource- the resource to check- Returns:
- the corresponding media type, or
nullif none found
setHeaders
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- current servlet responseresource- the identified resource (nevernull)mediaType- the resource's media type (nevernull)- Throws:
IOException- in case of errors while setting the headers