1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.web.servlet.resource;
18
19 import java.util.List;
20 import javax.servlet.http.HttpServletRequest;
21
22 import org.springframework.cache.Cache;
23 import org.springframework.cache.CacheManager;
24 import org.springframework.core.io.Resource;
25 import org.springframework.util.Assert;
26
27
28
29
30
31
32
33
34
35 public class CachingResourceResolver extends AbstractResourceResolver {
36
37 public static final String RESOLVED_RESOURCE_CACHE_KEY_PREFIX = "resolvedResource:";
38
39 public static final String RESOLVED_URL_PATH_CACHE_KEY_PREFIX = "resolvedUrlPath:";
40
41
42 private final Cache cache;
43
44 public CachingResourceResolver(CacheManager cacheManager, String cacheName) {
45 this(cacheManager.getCache(cacheName));
46 }
47
48 public CachingResourceResolver(Cache cache) {
49 Assert.notNull(cache, "'cache' is required");
50 this.cache = cache;
51 }
52
53
54
55
56 public Cache getCache() {
57 return this.cache;
58 }
59
60 @Override
61 protected Resource resolveResourceInternal(HttpServletRequest request, String requestPath,
62 List<? extends Resource> locations, ResourceResolverChain chain) {
63
64 String key = RESOLVED_RESOURCE_CACHE_KEY_PREFIX + requestPath;
65 Resource resource = this.cache.get(key, Resource.class);
66
67 if (resource != null) {
68 if (logger.isTraceEnabled()) {
69 logger.trace("Found match");
70 }
71 return resource;
72 }
73
74 resource = chain.resolveResource(request, requestPath, locations);
75 if (resource != null) {
76 if (logger.isTraceEnabled()) {
77 logger.trace("Putting resolved resource in cache");
78 }
79 this.cache.put(key, resource);
80 }
81
82 return resource;
83 }
84
85 @Override
86 protected String resolveUrlPathInternal(String resourceUrlPath,
87 List<? extends Resource> locations, ResourceResolverChain chain) {
88
89 String key = RESOLVED_URL_PATH_CACHE_KEY_PREFIX + resourceUrlPath;
90 String resolvedUrlPath = this.cache.get(key, String.class);
91
92 if (resolvedUrlPath != null) {
93 if (logger.isTraceEnabled()) {
94 logger.trace("Found match");
95 }
96 return resolvedUrlPath;
97 }
98
99 resolvedUrlPath = chain.resolveUrlPath(resourceUrlPath, locations);
100 if (resolvedUrlPath != null) {
101 if (logger.isTraceEnabled()) {
102 logger.trace("Putting resolved resource URL path in cache");
103 }
104 this.cache.put(key, resolvedUrlPath);
105 }
106
107 return resolvedUrlPath;
108 }
109
110 }