类 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
- 所有已实现的接口:
Aware
,InitializingBean
,ApplicationContextAware
,EmbeddedValueResolverAware
,ServletContextAware
,CorsConfigurationSource
,HttpRequestHandler
public class ResourceHttpRequestHandler extends WebContentGenerator implements HttpRequestHandler, EmbeddedValueResolverAware, 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
andresourceTransformer
chains to support arbitrary resolution and transformation of resources being served. By default aPathResourceResolver
simply finds resources based on the configured "locations". An application can configure additional resolvers and transformers such as theVersionResourceResolver
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 a304
status code will be returned as appropriate, avoiding unnecessary overhead for resources that are already cached by the client.- 从以下版本开始:
- 3.0.4
- 作者:
- Keith Donald, Jeremy Grelle, Juergen Hoeller, Arjen Poutsma, Brian Clozel, Rossen Stoyanchev
字段概要
从类继承的字段 org.springframework.web.servlet.support.WebContentGenerator
HEADER_CACHE_CONTROL, METHOD_GET, METHOD_HEAD, METHOD_POST
构造器概要
构造器 构造器 说明 ResourceHttpRequestHandler()
方法概要
所有方法 实例方法 具体方法 已过时的方法 修饰符和类型 方法 说明 void
afterPropertiesSet()
Invoked by the containingBeanFactory
after it has set all bean properties and satisfiedBeanFactoryAware
,ApplicationContextAware
etc.ContentNegotiationManager
getContentNegotiationManager()
已过时。as of 5.2.4.CorsConfiguration
getCorsConfiguration(HttpServletRequest request)
Return the specified CORS configuration.List<Resource>
getLocations()
Return the configuredList
ofResource
locations.protected MediaType
getMediaType(HttpServletRequest request, Resource resource)
Determine the media type for the given request and the resource matched to it.Map<String,MediaType>
getMediaTypes()
Return theconfigured
media types.protected Resource
getResource(HttpServletRequest request)
ResourceHttpMessageConverter
getResourceHttpMessageConverter()
Return the configured resource 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.UrlPathHelper
getUrlPathHelper()
The configuredUrlPathHelper
.void
handleRequest(HttpServletRequest request, HttpServletResponse response)
Processes a resource request.protected void
initAllowedLocations()
Look for aPathResourceResolver
among the configured resource resolvers and set itsallowedLocations
property (if empty) to match thelocations
configured on this class.protected PathExtensionContentNegotiationStrategy
initContentNegotiationStrategy()
已过时。as of 5.2.4 this method returnsnull
, and if a sub-class 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)
Identifies invalid resource paths.protected String
processPath(String path)
Process the given resource path.void
setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager)
已过时。as of 5.2.4 in favor of usingsetMediaTypes(Map)
with mappings possibly obtained fromContentNegotiationManager.getMediaTypeMappings()
.void
setCorsConfiguration(CorsConfiguration corsConfiguration)
Specify the CORS configuration for resources served by this handler.void
setEmbeddedValueResolver(StringValueResolver resolver)
Set the StringValueResolver to use for resolving embedded definition values.protected void
setHeaders(HttpServletResponse response, Resource resource, MediaType mediaType)
Set headers on the given servlet response.void
setLocations(List<Resource> locations)
Set theList
ofResource
locations to use as sources for serving static resources.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.void
setMediaTypes(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.void
setResourceHttpMessageConverter(ResourceHttpMessageConverter messageConverter)
Configure theResourceHttpMessageConverter
to use.void
setResourceRegionHttpMessageConverter(ResourceRegionHttpMessageConverter messageConverter)
Configure theResourceRegionHttpMessageConverter
to use.void
setResourceResolvers(List<ResourceResolver> resourceResolvers)
Configure the list ofResourceResolvers
to use.void
setResourceTransformers(List<ResourceTransformer> resourceTransformers)
Configure the list ofResourceTransformers
to use.void
setUrlPathHelper(UrlPathHelper urlPathHelper)
Provide a reference to theUrlPathHelper
used to map requests to static resources.String
toString()
从类继承的方法 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
从类继承的方法 org.springframework.web.context.support.WebApplicationObjectSupport
getServletContext, getTempDir, getWebApplicationContext, initApplicationContext, initServletContext, isContextRequired, setServletContext
从类继承的方法 org.springframework.context.support.ApplicationObjectSupport
getApplicationContext, getMessageSourceAccessor, initApplicationContext, obtainApplicationContext, requiredContextClass, setApplicationContext
构造器详细资料
ResourceHttpRequestHandler
public ResourceHttpRequestHandler()
方法详细资料
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"
.- 从以下版本开始:
- 4.3.13
setLocations
public void setLocations(List<Resource> locations)
Set theList
ofResource
locations to use as sources for serving static resources.
getLocations
public List<Resource> getLocations()
Return the configuredList
ofResource
locations.Note that if
locationValues
are provided, instead of loaded Resource-based locations, this method will return empty until after initialization viaafterPropertiesSet()
.
setResourceResolvers
public void setResourceResolvers(@Nullable List<ResourceResolver> resourceResolvers)
Configure the list ofResourceResolvers
to use.By default
PathResourceResolver
is configured. If using this property, it is recommended to addPathResourceResolver
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 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(@Nullable ResourceHttpMessageConverter messageConverter)
Configure theResourceHttpMessageConverter
to use.By default a
ResourceHttpMessageConverter
will be configured.- 从以下版本开始:
- 4.3
getResourceHttpMessageConverter
@Nullable public ResourceHttpMessageConverter getResourceHttpMessageConverter()
Return the configured resource converter.- 从以下版本开始:
- 4.3
setResourceRegionHttpMessageConverter
public void setResourceRegionHttpMessageConverter(@Nullable ResourceRegionHttpMessageConverter messageConverter)
Configure theResourceRegionHttpMessageConverter
to use.By default a
ResourceRegionHttpMessageConverter
will be configured.- 从以下版本开始:
- 4.3
getResourceRegionHttpMessageConverter
@Nullable public ResourceRegionHttpMessageConverter getResourceRegionHttpMessageConverter()
Return the configured resource region converter.- 从以下版本开始:
- 4.3
setContentNegotiationManager
@Deprecated public void setContentNegotiationManager(@Nullable ContentNegotiationManager contentNegotiationManager)
已过时。as of 5.2.4 in favor of usingsetMediaTypes(Map)
with mappings possibly obtained fromContentNegotiationManager.getMediaTypeMappings()
.Configure aContentNegotiationManager
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.- 从以下版本开始:
- 4.3
getContentNegotiationManager
@Nullable @Deprecated public ContentNegotiationManager getContentNegotiationManager()
已过时。as of 5.2.4.Return the configured content negotiation manager.- 从以下版本开始:
- 4.3
setMediaTypes
public void setMediaTypes(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.Use of this method is typically not necessary since mappings are otherwise determined via
ServletContext.getMimeType(String)
or viaMediaTypeFactory.getMediaType(Resource)
.- 参数:
mediaTypes
- media type mappings- 从以下版本开始:
- 5.2.4
getMediaTypes
public Map<String,MediaType> getMediaTypes()
Return theconfigured
media types.- 从以下版本开始:
- 5.2.4
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
@Nullable public CorsConfiguration getCorsConfiguration(HttpServletRequest request)
Return the specified CORS configuration.- 指定者:
getCorsConfiguration
在接口中CorsConfigurationSource
- 返回:
- the associated
CorsConfiguration
, ornull
if none
setUrlPathHelper
public void setUrlPathHelper(@Nullable UrlPathHelper urlPathHelper)
Provide a reference to theUrlPathHelper
used to map requests to static resources. This helps to derive information about the lookup path such as whether it is decoded or not.- 从以下版本开始:
- 4.3.13
getUrlPathHelper
@Nullable public UrlPathHelper getUrlPathHelper()
The configuredUrlPathHelper
.- 从以下版本开始:
- 4.3.13
setEmbeddedValueResolver
public void setEmbeddedValueResolver(StringValueResolver resolver)
从接口复制的说明:EmbeddedValueResolverAware
Set the StringValueResolver to use for resolving embedded definition values.
afterPropertiesSet
public void afterPropertiesSet() throws Exception
从接口复制的说明:InitializingBean
Invoked by the containingBeanFactory
after it has set all bean properties and satisfiedBeanFactoryAware
,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.
- 指定者:
afterPropertiesSet
在接口中InitializingBean
- 抛出:
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 aPathResourceResolver
among the configured resource resolvers and set itsallowedLocations
property (if empty) to match thelocations
configured on this class.
initContentNegotiationStrategy
@Nullable @Deprecated protected PathExtensionContentNegotiationStrategy initContentNegotiationStrategy()
已过时。as of 5.2.4 this method returnsnull
, and if a sub-class returns an actual instance,the instance is used only as a source of media type mappings, if it contains any. Please, usesetMediaTypes(Map)
instead, or if you need to change behavior, you can overridegetMediaType(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.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 theLast-Modified
header, and its value will be compared against the last-modified timestamp of the given resource, returning a304
status code if theLast-Modified
value is greater. If the resource is newer than theLast-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
在接口中HttpRequestHandler
- 参数:
request
- current HTTP requestresponse
- current HTTP response- 抛出:
ServletException
- in case of general errorsIOException
- in case of I/O errors
getResource
@Nullable protected Resource getResource(HttpServletRequest request) throws IOException
- 抛出:
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"
.
- 从以下版本开始:
- 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 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 validate- 返回:
true
if the path is invalid,false
otherwise- 从以下版本开始:
- 3.0.6
getMediaType
@Nullable 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:- 参数:
request
- the current requestresource
- the resource to check- 返回:
- the corresponding media type, or
null
if none found
setHeaders
protected void setHeaders(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.- 参数:
response
- current servlet responseresource
- the identified resource (nevernull
)mediaType
- the resource's media type (nevernull
)- 抛出:
IOException
- in case of errors while setting the headers