1 16 17 package org.springframework.web.servlet.view; 18 19 import java.util.HashMap ; 20 import java.util.Locale ; 21 import java.util.Map ; 22 23 import org.springframework.web.context.support.WebApplicationObjectSupport; 24 import org.springframework.web.servlet.View; 25 import org.springframework.web.servlet.ViewResolver; 26 27 40 public abstract class AbstractCachingViewResolver extends WebApplicationObjectSupport implements ViewResolver { 41 42 43 private boolean cache = true; 44 45 46 private final Map viewCache = new HashMap (); 47 48 49 55 public void setCache(boolean cache) { 56 this.cache = cache; 57 } 58 59 62 public boolean isCache() { 63 return cache; 64 } 65 66 67 public View resolveViewName(String viewName, Locale locale) throws Exception { 68 if (!isCache()) { 69 logger.warn("View caching is SWITCHED OFF -- DEVELOPMENT SETTING ONLY: This can severely impair performance"); 70 return createView(viewName, locale); 71 } 72 else { 73 Object cacheKey = getCacheKey(viewName, locale); 74 synchronized (this.viewCache) { 75 View view = (View) this.viewCache.get(cacheKey); 76 if (view == null) { 77 view = createView(viewName, locale); 79 this.viewCache.put(cacheKey, view); 80 if (logger.isDebugEnabled()) { 81 logger.debug("Cached view [" + cacheKey + "]"); 82 } 83 } 84 return view; 85 } 86 } 87 } 88 89 96 protected Object getCacheKey(String viewName, Locale locale) { 97 return viewName + "_" + locale; 98 } 99 100 109 public void removeFromCache(String viewName, Locale locale) { 110 if (!this.cache) { 111 logger.warn("View caching is SWITCHED OFF -- removal not necessary"); 112 } 113 else { 114 Object cacheKey = getCacheKey(viewName, locale); 115 Object cachedView = null; 116 synchronized (this.viewCache) { 117 cachedView = this.viewCache.remove(cacheKey); 118 } 119 if (cachedView == null) { 120 if (logger.isDebugEnabled()) { 122 logger.debug("No cached instance for view '" + cacheKey + "' was found"); 123 } 124 } 125 else { 126 if (logger.isDebugEnabled()) { 127 logger.debug("Cache for view " + cacheKey + " has been cleared"); 128 } 129 } 130 } 131 } 132 133 137 public void clearCache() { 138 logger.debug("Clearing entire view cache"); 139 synchronized (this.viewCache) { 140 this.viewCache.clear(); 141 } 142 } 143 144 145 158 protected View createView(String viewName, Locale locale) throws Exception { 159 return loadView(viewName, locale); 160 } 161 162 175 protected abstract View loadView(String viewName, Locale locale) throws Exception ; 176 177 } 178 | Popular Tags |