Refactor Resource URL generation and Servlet Filter

Renamed ResourceUrlMapper to ResourceUrlGenerator and refactored it
to be configured with Resource-serving HandlerMappings as opposed to
having them detected in the ApplicationContext through the
BeanPostProcessor contact.

Renamed and polished ResourceUrlEncodingFilter to ResourceUrlFilter
and added tests.
This commit is contained in:
Rossen Stoyanchev
2013-09-27 21:02:17 -04:00
parent 3c48b42106
commit 5a2e30c18b
6 changed files with 357 additions and 143 deletions

View File

@@ -23,7 +23,10 @@ import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.resource.PathResourceResolver;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import org.springframework.web.servlet.resource.ResourceResolver;
import org.springframework.web.servlet.resource.ResourceTransformer;
/**
* Encapsulates information required to create a resource handlers.
@@ -43,6 +46,11 @@ public class ResourceHandlerRegistration {
private Integer cachePeriod;
private List<ResourceResolver> resourceResolvers;
private List<ResourceTransformer> resourceTransformers;
/**
* Create a {@link ResourceHandlerRegistration} instance.
* @param resourceLoader a resource loader for turning a String location into a {@link Resource}
@@ -70,6 +78,23 @@ public class ResourceHandlerRegistration {
return this;
}
/**
* Configure the list of {@link ResourceResolver}s to use.
* <p>
* By default {@link PathResourceResolver} is configured. If using this property, it
* is recommended to add {@link PathResourceResolver} as the last resolver.
*/
public void setResourceResolvers(List<ResourceResolver> resourceResolvers) {
this.resourceResolvers = resourceResolvers;
}
/**
* Configure the list of {@link ResourceTransformer}s to use.
*/
public void setResourceTransformers(List<ResourceTransformer> transformers) {
this.resourceTransformers = transformers;
}
/**
* Specify the cache period for the resources served by the resource handler, in seconds. The default is to not
* send any cache headers but to rely on last-modified timestamps only. Set to 0 in order to send cache headers
@@ -95,9 +120,15 @@ public class ResourceHandlerRegistration {
protected ResourceHttpRequestHandler getRequestHandler() {
Assert.isTrue(!CollectionUtils.isEmpty(locations), "At least one location is required for resource handling.");
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler.setLocations(locations);
if (cachePeriod != null) {
requestHandler.setCacheSeconds(cachePeriod);
if (this.resourceResolvers != null) {
requestHandler.setResourceResolvers(this.resourceResolvers);
}
if (this.resourceTransformers != null) {
requestHandler.setResourceTransformers(this.resourceTransformers);
}
requestHandler.setLocations(this.locations);
if (this.cachePeriod != null) {
requestHandler.setCacheSeconds(this.cachePeriod);
}
return requestHandler;
}

View File

@@ -17,6 +17,9 @@
package org.springframework.web.servlet.resource;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
@@ -31,13 +34,17 @@ import org.springframework.web.util.UrlPathHelper;
/**
* A filter that wraps the {@link HttpServletResponse} and overrides its
* {@link HttpServletResponse#encodeURL(String) encodeURL} method in order to generate
* resource URL links via {@link ResourceUrlGenerator}.
*
* @author Jeremy Grelle
* @author Rossen Stoyanchev
* @since 4.0
*/
public class ResourceUrlEncodingFilter extends OncePerRequestFilter {
public class ResourceUrlFilter extends OncePerRequestFilter {
private ResourceUrlMapper mapper;
private Set<ResourceUrlGenerator> resourceUrlGenerators;
@Override
@@ -49,8 +56,10 @@ public class ResourceUrlEncodingFilter extends OncePerRequestFilter {
@Override
protected void initFilterBean() throws ServletException {
WebApplicationContext appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
this.mapper = appContext.getBean(ResourceUrlMapper.class);
WebApplicationContext cxt = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
Map<String, ResourceUrlGenerator> beans = cxt.getBeansOfType(ResourceUrlGenerator.class);
this.resourceUrlGenerators = new LinkedHashSet<ResourceUrlGenerator>();
this.resourceUrlGenerators.addAll(beans.values());
}
@@ -60,35 +69,30 @@ public class ResourceUrlEncodingFilter extends OncePerRequestFilter {
private String pathPrefix;
private ResourceUrlResponseWrapper(HttpServletRequest request, HttpServletResponse wrapped) {
super(wrapped);
this.pathPrefix = pathHelper.getContextPath(request);
String servletPath = pathHelper.getServletPath(request);
String appPath = pathHelper.getPathWithinApplication(request);
//This accounts for the behavior when servlet is mapped to "/"
if (!servletPath.equals(appPath)) {
this.pathPrefix += pathHelper.getServletPath(request);
}
String requestUri = this.pathHelper.getRequestUri(request);
String lookupPath = this.pathHelper.getLookupPathForRequest(request);
this.pathPrefix = requestUri.replace(lookupPath, "");
}
@Override
public String encodeURL(String url) {
if(url.startsWith(pathPrefix)) {
String relativeUrl = url.replaceFirst(pathPrefix, "");
if(url.startsWith(this.pathPrefix)) {
String relativeUrl = url.replaceFirst(this.pathPrefix, "");
if (!relativeUrl.startsWith("/")) {
relativeUrl = "/" + relativeUrl;
}
if (mapper.isResourceUrl(relativeUrl)) {
String resourceUrl = mapper.getUrlForResource(relativeUrl);
for (ResourceUrlGenerator generator : resourceUrlGenerators) {
String resourceUrl = generator.getResourceUrl(relativeUrl);
if (resourceUrl != null) {
return resourceUrl;
return super.encodeURL(this.pathPrefix + resourceUrl);
}
}
}
return super.encodeURL(url);
}
}
}

View File

@@ -0,0 +1,129 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import org.springframework.core.io.Resource;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
/**
* A helper class for generating the URL for a resource. Given knowledge of all configured
* resource handler mappings (see {@link #setResourceHandlerMappings(List)}), it can
* determine whether a given path is a path to a resource, as well as what URL should be
* sent to the client to access that resource. This is essentially the reverse of
* resolving an incoming request URL to a resource.
*
* @author Rossen Stoyanchev
* @since 4.0
*/
public class ResourceUrlGenerator {
private final List<ResourceMapping> resourceMappings = new ArrayList<ResourceMapping>();
/**
* Configure this instance with the handler mappings used to serve resources. It is
* expected that the handler mapping URL map contains handlers of type
* {@link ResourceHttpRequestHandler}.
*
* @param handlerMappings resource handler mappings
*/
public void setResourceHandlerMappings(List<SimpleUrlHandlerMapping> handlerMappings) {
this.resourceMappings.clear();
if (handlerMappings == null) {
return;
}
for (SimpleUrlHandlerMapping handlerMapping : handlerMappings) {
PathMatcher pathMatcher = handlerMapping.getPathMatcher();
for(Entry<String, ?> entry : handlerMapping.getUrlMap().entrySet()) {
Object value = entry.getValue();
if (value instanceof ResourceHttpRequestHandler) {
ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) value;
String pattern = entry.getKey();
List<ResourceResolver> resolvers = handler.getResourceResolvers();
List<Resource> locations = handler.getLocations();
this.resourceMappings.add(new ResourceMapping(pattern, pathMatcher, resolvers, locations));
}
}
}
}
/**
* Resolve the given resource path to a URL path. This is useful when rendering URL
* links to clients to determine the actual URL to use.
*
* @param candidatePath the resource path to resolve
*
* @return the resolved URL path or {@code null} if the given path does not match to
* any resource or otherwise could not be resolved to a resource URL path
*/
public String getResourceUrl(String candidatePath) {
for (ResourceMapping mapping : this.resourceMappings) {
String url = mapping.getUrlForResource(candidatePath);
if (url != null) {
return url;
}
}
return null;
}
private static class ResourceMapping {
private final String pattern;
private final PathMatcher pathMatcher;
private final List<ResourceResolver> resolvers;
private final List<Resource> locations;
public ResourceMapping(String pattern, PathMatcher pathMatcher,
List<ResourceResolver> resolvers, List<Resource> locations) {
this.pattern = pattern;
this.pathMatcher = pathMatcher;
this.resolvers = resolvers;
this.locations = locations;
}
public String getUrlForResource(String candidatePath) {
if (this.pathMatcher.match(this.pattern, candidatePath)) {
String pathWithinMapping = this.pathMatcher.extractPathWithinPattern(this.pattern, candidatePath);
String pathMapping = candidatePath.replace(pathWithinMapping, "");
DefaultResourceResolverChain chain = new DefaultResourceResolverChain(this.resolvers);
String url = chain.resolveUrlPath(pathWithinMapping, this.locations);
if (url != null) {
return pathMapping + url;
}
}
return null;
}
}
}

View File

@@ -1,106 +0,0 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.OrderComparator;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ClassUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
/**
*
* @author Jeremy Grelle
* @since 4.0
*/
public class ResourceUrlMapper implements BeanPostProcessor, ApplicationListener<ContextRefreshedEvent>{
private final Map<String, ResourceHttpRequestHandler> handlers = new LinkedHashMap<String, ResourceHttpRequestHandler>();
private final List<SimpleUrlHandlerMapping> mappings = new ArrayList<SimpleUrlHandlerMapping>();
private final PathMatcher matcher = new AntPathMatcher();
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
if (ClassUtils.isAssignableValue(SimpleUrlHandlerMapping.class, bean)) {
SimpleUrlHandlerMapping mapping = (SimpleUrlHandlerMapping) bean;
for(Entry<String, ?> mappingEntry : mapping.getUrlMap().entrySet()) {
Object val = mappingEntry.getValue();
if (val instanceof ResourceHttpRequestHandler) {
this.mappings.add(mapping);
}
}
}
return bean;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
OrderComparator.sort(this.mappings);
for (SimpleUrlHandlerMapping mapping : mappings) {
for(Entry<String, ?> mappingEntry : mapping.getUrlMap().entrySet()) {
Object val = mappingEntry.getValue();
this.handlers.put(mappingEntry.getKey(), (ResourceHttpRequestHandler) val);
}
}
}
public String getUrlForResource(String resourcePath) {
for (Entry<String, ResourceHttpRequestHandler> mapping : this.handlers.entrySet()) {
if (matcher.match(mapping.getKey(), resourcePath)) {
ResourceHttpRequestHandler handler = mapping.getValue();
String nestedPath = matcher.extractPathWithinPattern(mapping.getKey(), resourcePath);
String prefix = resourcePath.replace(nestedPath, "");
List<ResourceResolver> resolvers = handler.getResourceResolvers();
DefaultResourceResolverChain chain = new DefaultResourceResolverChain(resolvers);
String url = chain.resolveUrlPath(nestedPath, handler.getLocations());
if (url != null) {
return prefix + url;
}
}
}
return null;
}
public boolean isResourceUrl(String relativeUrl) {
for (String mapping : this.handlers.keySet()) {
if (matcher.match(mapping, relativeUrl)) {
return true;
}
}
return false;
}
}