1 24 package org.riotfamily.common.web.view.freemarker; 25 26 import java.util.HashMap ; 27 import java.util.Iterator ; 28 import java.util.Locale ; 29 import java.util.Map ; 30 31 import javax.servlet.http.HttpServletRequest ; 32 import javax.servlet.http.HttpServletResponse ; 33 34 import org.riotfamily.common.web.view.MacroHelperFactory; 35 import org.springframework.web.servlet.support.RequestContextUtils; 36 import org.springframework.web.servlet.view.freemarker.FreeMarkerView; 37 38 47 public class RiotFreeMarkerView extends FreeMarkerView { 48 49 public static final String REQUEST_ATTRIBUTE = "request"; 50 51 public static final String MODEL_ATTRIBUTE = 52 RiotFreeMarkerView.class.getName() + ".model"; 53 54 private boolean allowModelOverride = true; 55 56 private boolean freeMarkerServletMode = false; 57 58 private Map macroHelperFactories; 59 60 public void setAllowModelOverride(boolean allowModelOverride) { 61 this.allowModelOverride = allowModelOverride; 62 } 63 64 public void setFreeMarkerServletMode(boolean freeMarkerServletMode) { 65 this.freeMarkerServletMode = freeMarkerServletMode; 66 } 67 68 public void setMacroHelperFactories(Map macroHelperFactories) { 69 this.macroHelperFactories = macroHelperFactories; 70 } 71 72 public void render(Map model, HttpServletRequest request, 73 HttpServletResponse response) throws Exception { 74 75 if (allowModelOverride) { 76 Map emptyModel = new HashMap (); 77 emptyModel.put(MODEL_ATTRIBUTE, model); 78 model = emptyModel; 79 } 80 super.render(model, request, response); 81 } 82 83 private void unwrapModel(Map model) { 84 Map originalModel = (Map ) model.remove(MODEL_ATTRIBUTE); 85 if (originalModel != null) { 86 model.putAll(originalModel); 87 } 88 } 89 90 protected void renderMergedTemplateModel(final Map model, 91 final HttpServletRequest request, 92 final HttpServletResponse response) 93 throws Exception { 94 95 unwrapModel(model); 96 model.put(REQUEST_ATTRIBUTE, request); 97 if (macroHelperFactories != null) { 98 Iterator it = macroHelperFactories.entrySet().iterator(); 99 while (it.hasNext()) { 100 Map.Entry entry = (Map.Entry ) it.next(); 101 MacroHelperFactory factory = (MacroHelperFactory) entry.getValue(); 102 model.put(entry.getKey(), factory.createMacroHelper(request, response)); 103 } 104 } 105 if (freeMarkerServletMode) { 106 super.doRender(model, request, response); 107 } 108 else { 109 if (logger.isDebugEnabled()) { 110 logger.debug("Rendering FreeMarker template [" + getUrl() 111 + "] in FreeMarkerView '" + getBeanName() + "'"); 112 } 113 Locale locale = RequestContextUtils.getLocale(request); 114 processTemplate(getTemplate(locale), model, response); 115 } 116 } 117 118 } 119 | Popular Tags |