KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > servlet > view > velocity > VelocityLayoutView


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.web.servlet.view.velocity;
18
19 import java.io.StringWriter JavaDoc;
20
21 import javax.servlet.http.HttpServletResponse JavaDoc;
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 /**
30  * VelocityLayoutView emulates the functionality offered by Velocity's
31  * VelocityLayoutServlet to ease page composition from different templates.
32  *
33  * <p>The <code>url</code> property should be set to the content template
34  * for the view, and the layout template location should be specified as
35  * <code>layoutUrl</code> property. A view can override the configured
36  * layout template location by setting the appropriate key (the default
37  * is "layout") in the content template.
38  *
39  * <p>When the view is rendered, the VelocityContext is first merged with
40  * the content template (specified by the <code>url</code> property) and
41  * then merged with the layout template to produce the final output.
42  *
43  * <p>The layout template can include the screen content through a
44  * VelocityContext variable (the default is "screen_content").
45  * At runtime, this variable will contain the rendered content template.
46  *
47  * @author Darren Davison
48  * @author Juergen Hoeller
49  * @since 1.2
50  * @see #setLayoutUrl
51  * @see #setLayoutKey
52  * @see #setScreenContentKey
53  */

54 public class VelocityLayoutView extends VelocityToolboxView {
55
56     /**
57      * The default {@link #setLayoutUrl(String) layout url}.
58      */

59     public static final String JavaDoc DEFAULT_LAYOUT_URL = "layout.vm";
60
61     /**
62      * The default {@link #setLayoutKey(String) layout key}.
63      */

64     public static final String JavaDoc DEFAULT_LAYOUT_KEY = "layout";
65
66     /**
67      * The default {@link #setScreenContentKey(String) screen content key}.
68      */

69     public static final String JavaDoc DEFAULT_SCREEN_CONTENT_KEY = "screen_content";
70
71
72     private String JavaDoc layoutUrl = DEFAULT_LAYOUT_URL;
73
74     private String JavaDoc layoutKey = DEFAULT_LAYOUT_KEY;
75
76     private String JavaDoc screenContentKey = DEFAULT_SCREEN_CONTENT_KEY;
77
78
79     /**
80      * Set the layout template to use. Default is {@link #DEFAULT_LAYOUT_URL "layout.vm"}.
81      * @param layoutUrl the template location (relative to the template
82      * root directory)
83      */

84     public void setLayoutUrl(String JavaDoc layoutUrl) {
85         this.layoutUrl = layoutUrl;
86     }
87
88     /**
89      * Set the context key used to specify an alternate layout to be used instead
90      * of the default layout. Screen content templates can override the layout
91      * template that they wish to be wrapped with by setting this value in the
92      * template, for example:<br>
93      * <code>#set( $layout = "MyLayout.vm" )</code>
94      * <p>Default key is {@link #DEFAULT_LAYOUT_KEY "layout"}, as illustrated above.
95      * @param layoutKey the name of the key you wish to use in your
96      * screen content templates to override the layout template
97      */

98     public void setLayoutKey(String JavaDoc layoutKey) {
99         this.layoutKey = layoutKey;
100     }
101
102     /**
103      * Set the name of the context key that will hold the content of
104      * the screen within the layout template. This key must be present
105      * in the layout template for the current screen to be rendered.
106      * <p>Default is {@link #DEFAULT_SCREEN_CONTENT_KEY "screen_content"}:
107      * accessed in VTL as <code>$screen_content</code>.
108      * @param screenContentKey the name of the screen content key to use
109      */

110     public void setScreenContentKey(String JavaDoc screenContentKey) {
111         this.screenContentKey = screenContentKey;
112     }
113
114
115     /**
116      * Overrides <code>VelocityView.checkTemplate()</code> to additionally check
117      * that both the layout template and the screen content template can be loaded.
118      * Note that during rendering of the screen content, the layout template
119      * can be changed which may invalidate any early checking done here.
120      */

121     protected void checkTemplate() throws ApplicationContextException {
122         super.checkTemplate();
123
124         try {
125             // Check that we can get the template, even if we might subsequently get it again.
126
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 JavaDoc ex) {
133             throw new ApplicationContextException(
134                     "Could not load Velocity template for URL [" + this.layoutUrl + "]", ex);
135         }
136     }
137
138     /**
139      * Overrides the normal rendering process in order to pre-process the Context,
140      * merging it with the screen template into a single value (identified by the
141      * value of screenContentKey). The layout template is then merged with the
142      * modified Context in the super class.
143      */

144     protected void doRender(Context context, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
145         renderScreenContent(context);
146
147         // Velocity context now includes any mappings that were defined
148
// (via #set) in screen content template.
149
// The screen template can overrule the layout by doing
150
// #set( $layout = "MyLayout.vm" )
151
String JavaDoc layoutUrlToUse = (String JavaDoc) 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             // No explicit layout URL given -> use default layout of this view.
159
layoutUrlToUse = this.layoutUrl;
160         }
161
162         mergeTemplate(getTemplate(layoutUrlToUse), context, response);
163     }
164
165     /**
166      * The resulting context contains any mappings from render, plus screen content.
167      */

168     private void renderScreenContent(Context velocityContext) throws Exception JavaDoc {
169         if (logger.isDebugEnabled()) {
170             logger.debug("Rendering screen content template [" + getUrl() + "]");
171         }
172
173         StringWriter JavaDoc sw = new StringWriter JavaDoc();
174         Template screenContentTemplate = getTemplate(getUrl());
175         screenContentTemplate.merge(velocityContext, sw);
176
177         // Put rendered content into Velocity context.
178
velocityContext.put(this.screenContentKey, sw.toString());
179     }
180
181 }
182
Popular Tags