public class ResourceHttpRequestHandler extends WebContentGenerator implements HttpRequestHandler, InitializingBean, CorsConfigurationSource
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.
HEADER_CACHE_CONTROL, METHOD_GET, METHOD_HEAD, METHOD_POST
Constructor and Description |
---|
ResourceHttpRequestHandler() |
Modifier and Type | Method and Description |
---|---|
void |
afterPropertiesSet()
Invoked by a BeanFactory after it has set all bean properties supplied
(and satisfied BeanFactoryAware and ApplicationContextAware).
|
ContentNegotiationManager |
getContentNegotiationManager()
Return the specified content negotiation manager.
|
CorsConfiguration |
getCorsConfiguration(HttpServletRequest request)
Return the specified CORS configuration.
|
List<Resource> |
getLocations()
Return the
List of Resource paths to use as sources
for serving static resources. |
protected MediaType |
getMediaType(HttpServletRequest request,
Resource resource)
Determine the media type for the given request and the resource matched
to it.
|
protected MediaType |
getMediaType(Resource resource)
Deprecated.
as of 4.3 this method is deprecated; please override
getMediaType(HttpServletRequest, Resource) instead. |
protected Resource |
getResource(HttpServletRequest request) |
ResourceHttpMessageConverter |
getResourceHttpMessageConverter()
Return the list of configured resource converters.
|
ResourceRegionHttpMessageConverter |
getResourceRegionHttpMessageConverter()
Return the list of configured resource region converters.
|
List<ResourceResolver> |
getResourceResolvers()
Return the list of configured resource resolvers.
|
List<ResourceTransformer> |
getResourceTransformers()
Return the list of configured resource transformers.
|
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 void |
initServletContext(ServletContext servletContext)
Subclasses may override this for custom initialization based
on the ServletContext that this application object runs in.
|
protected boolean |
isInvalidPath(String path)
Identifies invalid resource paths.
|
protected String |
processPath(String path)
Process the given resource path to be used.
|
void |
setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager)
Configure a
ContentNegotiationManager to determine the media types
for resources being served. |
void |
setCorsConfiguration(CorsConfiguration corsConfiguration)
Specify the CORS configuration for resources served by this handler.
|
protected void |
setHeaders(HttpServletResponse response,
Resource resource,
MediaType mediaType)
Set headers on the given servlet response.
|
void |
setLocations(List<Resource> locations)
Set the
List of Resource paths to use as sources
for serving static resources. |
void |
setResourceHttpMessageConverter(ResourceHttpMessageConverter resourceHttpMessageConverter)
Configure the
ResourceHttpMessageConverter to use. |
void |
setResourceRegionHttpMessageConverter(ResourceRegionHttpMessageConverter resourceRegionHttpMessageConverter)
Configure the
ResourceRegionHttpMessageConverter to use. |
void |
setResourceResolvers(List<ResourceResolver> resourceResolvers)
Configure the list of
ResourceResolver s to use. |
void |
setResourceTransformers(List<ResourceTransformer> resourceTransformers)
Configure the list of
ResourceTransformer s to use. |
String |
toString() |
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
getServletContext, getTempDir, getWebApplicationContext, initApplicationContext, isContextRequired, setServletContext
getApplicationContext, getMessageSourceAccessor, initApplicationContext, requiredContextClass, setApplicationContext
public void setLocations(List<Resource> locations)
List
of Resource
paths to use as sources
for serving static resources.public List<Resource> getLocations()
List
of Resource
paths to use as sources
for serving static resources.public void setResourceResolvers(List<ResourceResolver> resourceResolvers)
ResourceResolver
s to use.
By default PathResourceResolver
is configured. If using this property,
it is recommended to add PathResourceResolver
as the last resolver.
public List<ResourceResolver> getResourceResolvers()
public void setResourceTransformers(List<ResourceTransformer> resourceTransformers)
ResourceTransformer
s to use.
By default no transformers are configured for use.
public List<ResourceTransformer> getResourceTransformers()
public void setResourceHttpMessageConverter(ResourceHttpMessageConverter resourceHttpMessageConverter)
ResourceHttpMessageConverter
to use.
By default a ResourceHttpMessageConverter
will be configured.
public ResourceHttpMessageConverter getResourceHttpMessageConverter()
public void setResourceRegionHttpMessageConverter(ResourceRegionHttpMessageConverter resourceRegionHttpMessageConverter)
ResourceRegionHttpMessageConverter
to use.
By default a ResourceRegionHttpMessageConverter
will be configured.
public ResourceRegionHttpMessageConverter getResourceRegionHttpMessageConverter()
public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager)
ContentNegotiationManager
to determine the media types
for resources being served. If the manager contains a path
extension strategy it will be used to look up the file extension
of resources being served via
getMediaTypeForResource
. If that fails the check is then expanded
to use any configured content negotiation strategy against the request.
By default a ContentNegotiationManagerFactoryBean
with default
settings is used to create the manager. See the Javadoc of
ContentNegotiationManagerFactoryBean
for details
contentNegotiationManager
- the manager to usepublic ContentNegotiationManager getContentNegotiationManager()
public void setCorsConfiguration(CorsConfiguration corsConfiguration)
By default this is not set in which allows cross-origin requests.
public CorsConfiguration getCorsConfiguration(HttpServletRequest request)
getCorsConfiguration
in interface CorsConfigurationSource
CorsConfiguration
, or null
if noneprotected void initServletContext(ServletContext servletContext)
WebApplicationObjectSupport
The default implementation is empty. Called by
WebApplicationObjectSupport.initApplicationContext(org.springframework.context.ApplicationContext)
as well as WebApplicationObjectSupport.setServletContext(javax.servlet.ServletContext)
.
initServletContext
in class WebApplicationObjectSupport
servletContext
- the ServletContext that this application object runs in
(never null
)public void afterPropertiesSet() throws Exception
InitializingBean
This method allows the bean instance to perform initialization only possible when all bean properties have been set and to throw an exception in the event of misconfiguration.
afterPropertiesSet
in interface InitializingBean
Exception
- in the event of misconfiguration (such
as failure to set an essential property) or if initialization fails.protected void initAllowedLocations()
PathResourceResolver
among the configured resource
resolvers and set its allowedLocations
property (if empty) to
match the locations
configured on this class.public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
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.
handleRequest
in interface HttpRequestHandler
request
- current HTTP requestresponse
- current HTTP responseServletException
- in case of general errorsIOException
- in case of I/O errorsprotected Resource getResource(HttpServletRequest request) throws IOException
IOException
protected String processPath(String path)
The default implementation replaces any combination of leading '/' and
control characters (00-1F and 7F) with a single "/" or "". For example
" // /// //// foo/bar"
becomes "/foo/bar"
.
protected boolean isInvalidPath(String path)
StringUtils.cleanPath(java.lang.String)
.
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.
path
- the path to validatetrue
if the path is invalid, false
otherwiseprotected MediaType getMediaType(HttpServletRequest request, Resource resource)
PathExtensionContentNegotiationStrategy.getMediaTypeForResource(org.springframework.core.io.Resource)
and then expands to check against the request via
ContentNegotiationManager.resolveMediaTypes(org.springframework.web.context.request.NativeWebRequest)
.request
- the current requestresource
- the resource to checknull
if none found@Deprecated protected MediaType getMediaType(Resource resource)
getMediaType(HttpServletRequest, Resource)
instead.resource
- the resource to checknull
if none foundprotected void setHeaders(HttpServletResponse response, Resource resource, MediaType mediaType) throws IOException
response
- current servlet responseresource
- the identified resource (never null
)mediaType
- the resource's media type (never null
)IOException
- in case of errors while setting the headers