类 ResourceHttpRequestHandler

java.lang.Object
cn.taketoday.context.support.ApplicationObjectSupport
cn.taketoday.web.WebContentGenerator
cn.taketoday.web.resource.ResourceHttpRequestHandler
所有已实现的接口:
cn.taketoday.beans.factory.Aware, cn.taketoday.beans.factory.InitializingBean, cn.taketoday.context.ApplicationContextAware, cn.taketoday.context.expression.EmbeddedValueResolverAware, CorsConfigurationSource, HttpRequestHandler

public class ResourceHttpRequestHandler extends WebContentGenerator implements HttpRequestHandler, cn.taketoday.context.expression.EmbeddedValueResolverAware, cn.taketoday.beans.factory.InitializingBean, 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, 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.

从以下版本开始:
4.0
作者:
Keith Donald, Jeremy Grelle, Juergen Hoeller, Arjen Poutsma, Brian Clozel, Rossen Stoyanchev, Harry Yang
  • 字段详细资料

    • log

      private static final cn.taketoday.logging.Logger log
    • URL_RESOURCE_CHARSET_PREFIX

      private static final String URL_RESOURCE_CHARSET_PREFIX
      另请参阅:
    • locationValues

      private final ArrayList<String> locationValues
    • locationResources

      private final ArrayList<cn.taketoday.core.io.Resource> locationResources
    • locationsToUse

      private final ArrayList<cn.taketoday.core.io.Resource> locationsToUse
    • locationCharsets

      private final HashMap<cn.taketoday.core.io.Resource,Charset> locationCharsets
    • resourceResolvers

      private final ArrayList<ResourceResolver> resourceResolvers
    • resourceTransformers

      private final ArrayList<ResourceTransformer> resourceTransformers
    • resolvingChain

      @Nullable private ResourceResolvingChain resolvingChain
    • transformerChain

      @Nullable private ResourceTransformerChain transformerChain
    • resourceHttpMessageConverter

      @Nullable private ResourceHttpMessageConverter resourceHttpMessageConverter
    • resourceRegionHttpMessageConverter

      @Nullable private ResourceRegionHttpMessageConverter resourceRegionHttpMessageConverter
    • contentNegotiationManager

      @Nullable private ContentNegotiationManager contentNegotiationManager
    • mediaTypes

      private final Map<String,MediaType> mediaTypes
    • corsConfiguration

      @Nullable private CorsConfiguration corsConfiguration
    • useLastModified

      private boolean useLastModified
    • optimizeLocations

      private boolean optimizeLocations
    • embeddedValueResolver

      @Nullable private cn.taketoday.core.StringValueResolver embeddedValueResolver
    • notFoundHandler

      private HttpRequestHandler notFoundHandler
  • 构造器详细资料

    • ResourceHttpRequestHandler

      public ResourceHttpRequestHandler()
  • 方法详细资料

    • 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 (e.g. 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".

      另请参阅:
    • setLocations

      public void setLocations(List<cn.taketoday.core.io.Resource> locations)
      Configure locations to serve resources from as pre-resourced Resource's.
      另请参阅:
    • getLocations

      public List<cn.taketoday.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).

      另请参阅:
    • 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 ResourceHttpMessageConverter messageConverter)
      Configure the ResourceHttpMessageConverter to use.

      By default a ResourceHttpMessageConverter will be configured.

    • getResourceHttpMessageConverter

      @Nullable public ResourceHttpMessageConverter getResourceHttpMessageConverter()
      Return the configured resource converter.
    • setResourceRegionHttpMessageConverter

      public void setResourceRegionHttpMessageConverter(@Nullable ResourceRegionHttpMessageConverter messageConverter)
      Configure the ResourceRegionHttpMessageConverter to use.

      By default a ResourceRegionHttpMessageConverter will be configured.

    • getResourceRegionHttpMessageConverter

      @Nullable public ResourceRegionHttpMessageConverter getResourceRegionHttpMessageConverter()
      Return the configured resource region converter.
    • setContentNegotiationManager

      public void setContentNegotiationManager(@Nullable ContentNegotiationManager contentNegotiationManager)
      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.
    • getContentNegotiationManager

      @Nullable public ContentNegotiationManager getContentNegotiationManager()
      Return the configured content negotiation manager.
    • setMediaTypes

      public void setMediaTypes(Map<String,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).

      参数:
      mediaTypes - media type mappings
    • getMediaTypes

      public Map<String,MediaType> getMediaTypes()
      Return the configured media types.
    • setCorsConfiguration

      public void setCorsConfiguration(@Nullable 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(RequestContext request)
      Return the specified CORS configuration.
      指定者:
      getCorsConfiguration 在接口中 CorsConfigurationSource
      返回:
      the associated CorsConfiguration, or null if none
    • 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.

    • isUseLastModified

      public boolean isUseLastModified()
      Return whether the Resource.lastModified() information is used to drive HTTP responses when serving static resources.
    • 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.

    • 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.
    • setEmbeddedValueResolver

      public void setEmbeddedValueResolver(@Nullable cn.taketoday.core.StringValueResolver resolver)
      指定者:
      setEmbeddedValueResolver 在接口中 cn.taketoday.context.expression.EmbeddedValueResolverAware
    • setNotFoundHandler

      public void setNotFoundHandler(@Nullable HttpRequestHandler notFoundHandler)
      Set not found handler

      handle if resource not found

      参数:
      notFoundHandler - HttpRequestHandler can be null
      另请参阅:
    • afterPropertiesSet

      public void afterPropertiesSet() throws Exception
      指定者:
      afterPropertiesSet 在接口中 cn.taketoday.beans.factory.InitializingBean
      抛出:
      Exception
    • resolveResourceLocations

      private void resolveResourceLocations()
    • 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.
    • handleRequest

      public Object handleRequest(RequestContext request) throws Throwable
      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 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 在接口中 HttpRequestHandler
      参数:
      request - Current request context
      返回:
      Result to be handled by ReturnValueHandler
      抛出:
      Throwable - If any exception occurred
      另请参阅:
    • getResource

      @Nullable protected cn.taketoday.core.io.Resource getResource(RequestContext 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".
    • cleanDuplicateSlashes

      private String cleanDuplicateSlashes(String path)
    • cleanLeadingSlash

      private String cleanLeadingSlash(String path)
    • isInvalidEncodedPath

      private boolean isInvalidEncodedPath(String path)
      Check whether the given path contains invalid escape sequences.
      参数:
      path - the path to validate
      返回:
      true if the path is invalid, false otherwise
    • 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
    • getMediaType

      @Nullable protected MediaType getMediaType(RequestContext request, cn.taketoday.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.getMediaTypes(String)
      参数:
      request - the current request
      resource - the resource to check
      返回:
      the corresponding media type, or null if none found
    • setHeaders

      protected void setHeaders(RequestContext response, cn.taketoday.core.io.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 response
      resource - the identified resource (never null)
      mediaType - the resource's media type (never null)
      抛出:
      IOException - in case of errors while setting the headers
    • toString

      public String toString()
      覆盖:
      toString 在类中 Object
    • locationToString

      private String locationToString(List<cn.taketoday.core.io.Resource> locations)