1 16 17 package org.springframework.web.servlet.view.velocity; 18 19 import java.io.StringWriter ; 20 21 import javax.servlet.http.HttpServletResponse ; 22 23 import org.apache.velocity.Template; 24 import org.apache.velocity.context.Context; 25 import org.apache.velocity.exception.ResourceNotFoundException; 26 27 import org.springframework.context.ApplicationContextException; 28 29 54 public class VelocityLayoutView extends VelocityToolboxView { 55 56 59 public static final String DEFAULT_LAYOUT_URL = "layout.vm"; 60 61 64 public static final String DEFAULT_LAYOUT_KEY = "layout"; 65 66 69 public static final String DEFAULT_SCREEN_CONTENT_KEY = "screen_content"; 70 71 72 private String layoutUrl = DEFAULT_LAYOUT_URL; 73 74 private String layoutKey = DEFAULT_LAYOUT_KEY; 75 76 private String screenContentKey = DEFAULT_SCREEN_CONTENT_KEY; 77 78 79 84 public void setLayoutUrl(String layoutUrl) { 85 this.layoutUrl = layoutUrl; 86 } 87 88 98 public void setLayoutKey(String layoutKey) { 99 this.layoutKey = layoutKey; 100 } 101 102 110 public void setScreenContentKey(String screenContentKey) { 111 this.screenContentKey = screenContentKey; 112 } 113 114 115 121 protected void checkTemplate() throws ApplicationContextException { 122 super.checkTemplate(); 123 124 try { 125 getTemplate(this.layoutUrl); 127 } 128 catch (ResourceNotFoundException ex) { 129 throw new ApplicationContextException("Cannot find Velocity template for URL [" + this.layoutUrl + 130 "]: Did you specify the correct resource loader path?", ex); 131 } 132 catch (Exception ex) { 133 throw new ApplicationContextException( 134 "Could not load Velocity template for URL [" + this.layoutUrl + "]", ex); 135 } 136 } 137 138 144 protected void doRender(Context context, HttpServletResponse response) throws Exception { 145 renderScreenContent(context); 146 147 String layoutUrlToUse = (String ) context.get(this.layoutKey); 152 if (layoutUrlToUse != null) { 153 if (logger.isDebugEnabled()) { 154 logger.debug("Screen content template has requested layout [" + layoutUrlToUse + "]"); 155 } 156 } 157 else { 158 layoutUrlToUse = this.layoutUrl; 160 } 161 162 mergeTemplate(getTemplate(layoutUrlToUse), context, response); 163 } 164 165 168 private void renderScreenContent(Context velocityContext) throws Exception { 169 if (logger.isDebugEnabled()) { 170 logger.debug("Rendering screen content template [" + getUrl() + "]"); 171 } 172 173 StringWriter sw = new StringWriter (); 174 Template screenContentTemplate = getTemplate(getUrl()); 175 screenContentTemplate.merge(velocityContext, sw); 176 177 velocityContext.put(this.screenContentKey, sw.toString()); 179 } 180 181 } 182 | Popular Tags |