KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > views > freemarker > FreemarkerServlet


1 /*
2  * Copyright (c) 2002-2003 by OpenSymphony
3  * All rights reserved.
4  */

5 /*
6  * Created on 27/08/2003
7  *
8  */

9 package com.opensymphony.webwork.views.freemarker;
10
11 import com.opensymphony.webwork.ServletActionContext;
12 import com.opensymphony.xwork.util.OgnlValueStack;
13 import freemarker.template.*;
14
15 import javax.servlet.ServletContext JavaDoc;
16 import javax.servlet.ServletException JavaDoc;
17 import javax.servlet.http.HttpServlet JavaDoc;
18 import javax.servlet.http.HttpServletRequest JavaDoc;
19 import javax.servlet.http.HttpServletResponse JavaDoc;
20 import java.io.FileNotFoundException JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.util.Locale JavaDoc;
23
24
25 /**
26  * @author CameronBraid
27  * @deprecated Please use the FreemarkerResult result type instead
28  */

29 public class FreemarkerServlet extends HttpServlet JavaDoc {
30     //~ Instance fields ////////////////////////////////////////////////////////
31

32     protected Configuration configuration;
33
34     //~ Constructors ///////////////////////////////////////////////////////////
35

36     /**
37      *
38      */

39     public FreemarkerServlet() {
40         super();
41     }
42
43     //~ Methods ////////////////////////////////////////////////////////////////
44

45     final public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
46         request.setAttribute("webwork.freemarker.servlet", this);
47         process(request, response);
48     }
49
50     final public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
51         request.setAttribute("webwork.freemarker.servlet", this);
52         process(request, response);
53     }
54
55     public void init() throws ServletException JavaDoc {
56         try {
57             configuration = createConfiguration();
58         } catch (TemplateException e) {
59             throw new ServletException JavaDoc("could not configure Freemarker", e);
60         }
61     }
62
63     /**
64      * This method is called from {@link #process(HttpServletRequest, HttpServletResponse)} to obtain the
65      * FreeMarker object wrapper object that this result will use
66      * for adapting objects into
67      * template models.. This is a hook that allows you
68      * to custom-configure the wrapper object in a subclass.
69      * <p/>
70      * <b>
71      * The default implementation returns @see Configuration#getObjectWrapper()
72      * </b>
73      */

74     protected ObjectWrapper getObjectWrapper() {
75         return configuration.getObjectWrapper();
76     }
77
78     protected Configuration createConfiguration() throws TemplateException {
79         return FreemarkerManager.getInstance().getConfigruation(getServletContext());
80     }
81
82     protected TemplateModel createModel(ObjectWrapper wrapper, ServletContext JavaDoc servletContext, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws TemplateModelException {
83
84         OgnlValueStack stack = ServletActionContext.getContext().getValueStack();
85         Object JavaDoc action = null;
86         if (ServletActionContext.getContext().getActionInvocation() != null) {
87             action = ServletActionContext.getContext().getActionInvocation().getAction();
88         }
89         TemplateModel model = FreemarkerManager.getInstance().buildTemplateModel(stack, action, servletContext, request, response, wrapper);
90         return model;
91     }
92
93     /**
94      * Returns the locale used for the
95      * {@link Configuration#getTemplate(String, Locale)} call.
96      * The base implementation simply returns the locale setting of the
97      * configuration. Override this method to provide different behaviour, i.e.
98      * to use the locale indicated in the request.
99      */

100     protected Locale JavaDoc deduceLocale(String JavaDoc templatePath, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
101         return configuration.getLocale();
102     }
103
104     /**
105      * Called after the execution returns from template.process().
106      * This is a generic hook you might use in subclasses to perform a specific
107      * action after the template is processed. It will be invoked even if the
108      * template processing throws an exception. By default does nothing.
109      *
110      * @param request the actual HTTP request
111      * @param response the actual HTTP response
112      * @param template the template that was executed
113      * @param data the data that was passed to the template
114      */

115     protected void postTemplateProcess(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Template template, TemplateModel data) throws ServletException JavaDoc, IOException JavaDoc {
116     }
117
118     // /**
119
// * If the parameter "nocache" was set to true, generate a set of headers
120
// * that will advise the HTTP client not to cache the returned page.
121
// */
122
// private void setBrowserCachingPolicy(HttpServletResponse response)
123
// {
124
// if (nocache)
125
// {
126
// // HTTP 1.1 browsers should defeat caching on this header
127
// response.setHeader("Cache-Control", "no-cache");
128
// // HTTP 1.0 browsers should defeat caching on this header
129
// response.setHeader("Pragma", "no-cache");
130
// // Last resort for those that ignore all of the above
131
// response.setHeader("Expires", EXPIRATION_DATE);
132
// }
133
// }
134

135     /**
136      * Called before the execution is passed to template.process().
137      * This is a generic hook you might use in subclasses to perform a specific
138      * action before the template is processed. By default does nothing.
139      * A typical action to perform here is to inject application-specific
140      * objects into the model root
141      *
142      * @param request the actual HTTP request
143      * @param response the actual HTTP response
144      * @param template the template that will get executed
145      * @param data the data that will be passed to the template
146      * @return true to process the template, false to suppress template processing.
147      */

148     protected boolean preTemplateProcess(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Template template, TemplateModel data) throws ServletException JavaDoc, IOException JavaDoc {
149         return true;
150     }
151
152     /**
153      * Maps the request URL to a template path that is passed to
154      * {@link Configuration#getTemplate(String, Locale)}. You can override it
155      * (i.e. to provide advanced rewriting capabilities), but you are strongly
156      * encouraged to call the overridden method first, then only modify its
157      * return value.
158      *
159      * @param request the currently processed request
160      * @return a String representing the template path
161      */

162     protected String JavaDoc requestUrlToTemplatePath(HttpServletRequest JavaDoc request) {
163         // First, see if it is an included request
164
String JavaDoc includeServletPath = (String JavaDoc) request.getAttribute("javax.servlet.include.servlet_path");
165
166         if (includeServletPath != null) {
167             // Try path info; only if that's null (servlet is mapped to an
168
// URL extension instead of to prefix) use servlet path.
169
String JavaDoc includePathInfo = (String JavaDoc) request.getAttribute("javax.servlet.include.path_info");
170
171             return (includePathInfo == null) ? includeServletPath : includePathInfo;
172         }
173
174         // Seems that the servlet was not called as the result of a
175
// RequestDispatcher.include(...). Try pathInfo then servletPath again,
176
// only now directly on the request object:
177
String JavaDoc path = request.getPathInfo();
178
179         if (path != null) {
180             return path;
181         }
182
183         path = request.getServletPath();
184
185         if (path != null) {
186             return path;
187         }
188
189         // Seems that it is a servlet mapped with prefix, and there was no extra path info.
190
return "";
191     }
192
193     private void process(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
194         String JavaDoc path = requestUrlToTemplatePath(request);
195
196         Template template = null;
197
198         try {
199             template = configuration.getTemplate(path, deduceLocale(path, request, response));
200         } catch (FileNotFoundException JavaDoc e) {
201             response.sendError(HttpServletResponse.SC_NOT_FOUND);
202
203             return;
204         }
205
206         Object JavaDoc attrContentType = template.getCustomAttribute("content_type");
207
208         if (attrContentType != null) {
209             response.setContentType(attrContentType.toString());
210         } else {
211             response.setContentType("text/html; charset=" + template.getEncoding());
212         }
213
214         // // Set cache policy
215
// setBrowserCachingPolicy(response);
216
ServletContext JavaDoc servletContext = getServletContext();
217
218         try {
219             TemplateModel model = createModel(getObjectWrapper(), servletContext, request, response);
220
221             // Give subclasses a chance to hook into preprocessing
222
if (preTemplateProcess(request, response, template, model)) {
223                 try {
224                     // Process the template
225
template.process(model, response.getWriter());
226                 } finally {
227                     // Give subclasses a chance to hook into postprocessing
228
postTemplateProcess(request, response, template, model);
229                 }
230             }
231         } catch (TemplateException te) {
232             // only throw a servlet exception if not a debug handler
233
// this is what the original freemarker.ext.servlet.FreemarkerServlet does
234
if ((configuration.getTemplateExceptionHandler() != freemarker.template.TemplateExceptionHandler.HTML_DEBUG_HANDLER) && (configuration.getTemplateExceptionHandler() != freemarker.template.TemplateExceptionHandler.DEBUG_HANDLER)) {
235                 throw new ServletException JavaDoc(te);
236             }
237         }
238     }
239 }
240
Popular Tags