Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright 2014 Attila Szegedi, Daniel Dekany, Jonathan Revusky
    * 
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    * 
    * http://www.apache.org/licenses/LICENSE-2.0
    * 
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package freemarker.ext.servlet;
  
  import java.util.List;
  import java.util.Locale;
  
  import  javax.servlet.ServletContext;
  import  javax.servlet.ServletException;
  import  javax.servlet.http.HttpServlet;
  import  javax.servlet.http.HttpServletRequest;
  import  javax.servlet.http.HttpServletResponse;
  import  javax.servlet.http.HttpSession;
  
FreeMarker MVC View servlet that can be used similarly to JSP views. That is, you put the variables to expose into HTTP servlet request attributes, then forward to an FTL file (instead of to a JSP file) that's mapped to this servet (usually via the <url-pattern>*.ftl<url-pattern>). See web.xml example (and more) in the FreeMarker Manual!

Main features

  • It makes all request, request parameters, session, and servlet context attributes available to templates through Request, RequestParameters, Session, and Application variables.
  • The scope variables are also available via automatic scope discovery. That is, writing Application.attrName, Session.attrName, Request.attrName is not mandatory; it's enough to write attrName, and if no such variable was created in the template, it will search the variable in Request, and then in Session, and finally in Application.
  • It creates a variable with name JspTaglibs that can be used to load JSP taglibs. For example:
    <#assign dt=JspTaglibs["http://displaytag.sf.net"]> or <#assign tiles=JspTaglibs["/WEB-INF/struts-tiles.tld"]>.
  • A custom directive named include_page allows you to include the output of another servlet resource from your servlet container, just as if you used ServletRequest.getRequestDispatcher(path).include(): <@include_page path="/myWebapp/somePage.jsp"/>. You can also pass parameters to the newly included page by passing a hash named params: <@include_page path="/myWebapp/somePage.jsp" params= lang: "en", q="5"}/>. By default, the request parameters of the original request (the one being processed by FreemarkerServlet) are also inherited by the include. You can explicitly control this inheritance using the inherit_params parameter: <@include_page path="/myWebapp/somePage.jsp" params={lang: "en", q="5"} inherit_params=false/>.

Supported init-param-s

  • .INIT_PARAM_TEMPLATE_PATH: Specifies the location of the templates. By default, this is interpreted as a ServletContext reasource path, which practically means a web application directory relative path, or a WEB-INF/lib/*.jar/META-INF/resources-relative path (note that this last didn't work properly before FreeMarker 2.3.23).
    Alternatively, you can prepend it with file:// to indicate a literal path in the file system (i.e. file:///var/www/project/templates/). Note that three slashes were used to specify an absolute path.
    Also, you can prepend it with classpath:, like in classpath:com/example/templates, to indicate that you want to load templates from the specified package accessible through the Thread Context Class Loader of the thread that initializes this servlet.
    If incompatible_improvements is set to 2.3.22 (or higher), you can specify multiple comma separated locations inside square brackets, like: [ WEB-INF/templates, classpath:com/example/myapp/templates ]. This internally creates a MultiTemplateLoader. Note again that if incompatible_improvements isn't set to at least 2.3.22, the initial [ has no special meaning, and so this feature is unavailable.
    Any of the above can have a ?setting(name=value, ...) postfix to set the JavaBeans properties of the TemplateLoader created. For example, /templates?settings(attemptFileAccess=false, URLConnectionUsesCaches=true) calls WebappTemplateLoader.setAttemptFileAccess(boolean) and WebappTemplateLoader.setURLConnectionUsesCaches(Boolean) to tune the WebappTemplateLoader. For backward compatibility (not recommended!), you can use the class:// prefix, like in class://com/example/templates format, which is similar to classpath:, except that it uses the defining class loader of this servlet's class. This can cause template not found errors, if that class (in freemarer.jar usually) is not local to the web application, while the templates are.
    The default value is class:// (that is, the root of the class hierarchy), which is not recommended anymore, and should be overwritten with the init-param.
  • .INIT_PARAM_NO_CACHE: If set to true, generates headers in the response that advise the HTTP client not to cache the returned page. The default is false.
  • .INIT_PARAM_CONTENT_TYPE: If specified, response uses the specified Content-type HTTP header. The value may include the charset (e.g. "text/html; charset=ISO-8859-1"). If not specified, "text/html" is used. If the charset is not specified in this init-param, then the charset (encoding) of the actual template file will be used (in the response HTTP header and for encoding the output stream). Note that this setting can be overridden on a per-template basis by specifying a custom attribute named content_type in the attributes parameter of the <#ftl> directive.
  • .INIT_PARAM_BUFFER_SIZE: Sets the size of the output buffer in bytes, or if "KB" or "MB" is written after the number (like <param-value>256 KB</param-value>) then in kilobytes or megabytes. This corresponds to HttpServletResponse.setBufferSize(int). If the HttpServletResponse state doesn't allow changing the buffer size, it will silently do nothing. If this init param isn't specified, then the buffer size is not set by FreemarkerServlet in the HTTP response, which usually means that the default buffer size of the servlet container will be used.
  • .INIT_PARAM_EXCEPTION_ON_MISSING_TEMPLATE (since 2.3.22): If false (default, but not recommended), if a template is requested that's missing, this servlet responses with a HTTP 404 "Not found" error, and only logs the problem with debug level. If true (recommended), the servlet will log the issue with error level, then throws an exception that bubbles up to the servlet container, which usually then creates a HTTP 500 "Internal server error" response (and maybe logs the event into the container log). See "Error handling" later for more!
  • .INIT_PARAM_META_INF_TLD_LOCATIONS (since 2.3.22): Comma separated list of items, each is either .META_INF_TLD_LOCATION_WEB_INF_PER_LIB_JARS, or .META_INF_TLD_LOCATION_CLASSPATH optionally followed by colon and a regular expression, or .META_INF_TLD_LOCATION_CLEAR. For example <param-value>classpath:.*myoverride.*\.jar$, webInfPerLibJars, classpath:.*taglib.*\.jar$</param-value>, or <param-value>classpath</param-value>. (Whitespace around the commas and list items will be ignored.) See TaglibFactory.setMetaInfTldSources(List) for more information. Defaults to a list that contains .META_INF_TLD_LOCATION_WEB_INF_PER_LIB_JARS only (can be overridden with createDefaultMetaInfTldSources()). Note that this can be also specified with the .SYSTEM_PROPERTY_META_INF_TLD_SOURCES system property. If both the init-param and the system property exists, the sources listed in the system property will be added after those specified by the init-param. This is where the special entry, .META_INF_TLD_LOCATION_CLEAR comes handy, as it will remove all previous list items. (An intended usage of the system property is setting it to clear, classpath in the Eclipse run configuration if you are running the application without putting the dependency jar-s into WEB-INF/lib.) Also, note that further classpath:<pattern> items are added automatically at the end of this list based on Jetty's "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern" servlet context attribute.
  • .INIT_PARAM_CLASSPATH_TLDS (since 2.3.22): Comma separated list of paths; see TaglibFactory.setClasspathTlds(List). Whitespace around the list items will be ignored. Defaults to no paths (can be overidden with createDefaultClassPathTlds()). Note that this can also be specified with the .SYSTEM_PROPERTY_CLASSPATH_TLDS system property. If both the init-param and the system property exists, the items listed in system property will be added after those specified by the init-param.
  • "Debug": Deprecated, has no effect since 2.3.22. (Earlier it has enabled/disabled sending debug-level log messages to the servlet container log, but this servlet doesn't log debug level messages into the servlet container log anymore, only into the FreeMarker log.)
  • The following init-params are supported only for backward compatibility, and their usage is discouraged: TemplateUpdateInterval, DefaultEncoding, ObjectWrapper, TemplateExceptionHandler. Instead, use init-params with the setting names documented at Configuration.setSetting(String, String), such as object_wrapper.
  • Any other init-params will be interpreted as Configuration-level FreeMarker setting. See the possible names and values at Configuration.setSetting(String, String).

Error handling

Notes:

  • Logging below, where not said otherwise, always refers to logging with FreeMarker's logging facility (see Logger), under the "freemarker.servlet" category.
  • Throwing a ServletException to the servlet container is mentioned at a few places below. That in practice usually means HTTP 500 "Internal server error" response, and maybe a log entry in the servlet container's log.

Errors types:

  • If the servlet initialization fails, the servlet won't be started as usual. The cause is usually logged with error level. When it isn't, check the servlet container's log.
  • If the requested template doesn't exist, by default the servlet returns a HTTP 404 "Not found" response, and logs the problem with debug level. Responding with HTTP 404 is how JSP behaves, but it's actually not a recommended setting anymore. By setting .INIT_PARAM_EXCEPTION_ON_MISSING_TEMPLATE init-param to true (recommended), it will instead log the problem with error level, then the servlet throws ServletException to the servlet container (with the proper cause exception). After all, if the visited URL had an associated "action" but the template behind it is missing, that's an internal server error, not a wrong URL.
  • If the template contains parsing errors, it will log it with error level, then the servlet throws ServletException to the servlet container (with the proper cause exception).
  • If the template throws exception during its execution, and the value of the template_exception_handler init-param is rethrow (recommended), it will log it with error level and then the servlet throws ServletException to the servlet container (with the proper cause exception). But beware, the default value of the template_exception_handler init-param is html_debug, which is for development only! Set it to rethrow for production. The html_debug (and debug) handlers will print error details to the page and then commit the HTTP response with response code 200 "OK", thus, the server wont be able roll back the response and send back an HTTP 500 page. This is so that the template developers will see the error without digging the logs.
 
 public class FreemarkerServlet extends HttpServlet
 {
     private static final Logger LOG = Logger.getLogger("freemarker.servlet");
     private static final Logger LOG_RT = Logger.getLogger("freemarker.runtime");
 
     public static final long serialVersionUID = -2440216393145762479L;

    
Init-param name - see the FreemarkerServlet class documentation about the init-params. (This init-param has existed long before 2.3.22, but this constant was only added then.)

Since:
2.3.22
 
     public static final String INIT_PARAM_TEMPLATE_PATH = "TemplatePath";
    
    
Init-param name - see the FreemarkerServlet class documentation about the init-params. (This init-param has existed long before 2.3.22, but this constant was only added then.)

Since:
2.3.22
 
     public static final String INIT_PARAM_NO_CACHE = "NoCache";

    
Init-param name - see the FreemarkerServlet class documentation about the init-params. (This init-param has existed long before 2.3.22, but this constant was only added then.)

Since:
2.3.22
 
     public static final String INIT_PARAM_CONTENT_TYPE = "ContentType";

    
Init-param name - see the FreemarkerServlet class documentation about the init-params.

Since:
2.3.22
 
     public static final String INIT_PARAM_BUFFER_SIZE = "BufferSize";
    
    
Init-param name - see the FreemarkerServlet class documentation about the init-params.

Since:
2.3.22
 
     public static final String INIT_PARAM_META_INF_TLD_LOCATIONS = "MetaInfTldSources";

    
Init-param name - see the FreemarkerServlet class documentation about the init-params.

Since:
2.3.22
 
     public static final String INIT_PARAM_EXCEPTION_ON_MISSING_TEMPLATE = "ExceptionOnMissingTemplate";
    
    
Init-param name - see the FreemarkerServlet class documentation about the init-params.

Since:
2.3.22
 
     public static final String INIT_PARAM_CLASSPATH_TLDS = "ClasspathTlds";
     
     private static final String INIT_PARAM_DEBUG = "Debug";
 
     private static final String DEPR_INITPARAM_TEMPLATE_DELAY = "TemplateDelay";
     private static final String DEPR_INITPARAM_ENCODING = "DefaultEncoding";
     private static final String DEPR_INITPARAM_OBJECT_WRAPPER = "ObjectWrapper";
     private static final String DEPR_INITPARAM_WRAPPER_SIMPLE = "simple";
     private static final String DEPR_INITPARAM_WRAPPER_BEANS = "beans";
     private static final String DEPR_INITPARAM_WRAPPER_JYTHON = "jython";
     private static final String DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER = "TemplateExceptionHandler";
     private static final String DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_RETHROW = "rethrow";
     private static final String DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_DEBUG = "debug";
     private static final String DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_HTML_DEBUG = "htmlDebug";
     private static final String DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_IGNORE = "ignore";
     private static final String DEPR_INITPARAM_DEBUG = "debug";
     
     private static final String DEFAULT_CONTENT_TYPE = "text/html";

    
When set, the items defined in it will be added after those coming from the .INIT_PARAM_META_INF_TLD_LOCATIONS init-param. The value syntax is the same as of the init-param. Note that .META_INF_TLD_LOCATION_CLEAR can be used to re-start the list, rather than continue it.

Since:
2.3.22
 
     public static final String SYSTEM_PROPERTY_META_INF_TLD_SOURCES = "org.freemarker.jsp.metaInfTldSources";

    
When set, the items defined in it will be added after those coming from the .INIT_PARAM_CLASSPATH_TLDS init-param. The value syntax is the same as of the init-param.

Since:
2.3.22
 
     public static final String SYSTEM_PROPERTY_CLASSPATH_TLDS = "org.freemarker.jsp.classpathTlds";
    
    
Used as part of the value of the .INIT_PARAM_META_INF_TLD_LOCATIONS init-param.

Since:
2.3.22
 
     public static final String META_INF_TLD_LOCATION_WEB_INF_PER_LIB_JARS = "webInfPerLibJars";
    
    
Used as part of the value of the .INIT_PARAM_META_INF_TLD_LOCATIONS init-param.

Since:
2.3.22
 
     public static final String META_INF_TLD_LOCATION_CLASSPATH = "classpath";
    
    
Used as part of the value of the .INIT_PARAM_META_INF_TLD_LOCATIONS init-param.

Since:
2.3.22
 
     public static final String META_INF_TLD_LOCATION_CLEAR = "clear";
     
 
     public static final String KEY_REQUEST = "Request";
     public static final String KEY_INCLUDE = "include_page";
     public static final String KEY_REQUEST_PRIVATE = "__FreeMarkerServlet.Request__";
     public static final String KEY_REQUEST_PARAMETERS = "RequestParameters";
     public static final String KEY_SESSION = "Session";
     public static final String KEY_APPLICATION = "Application";
     public static final String KEY_APPLICATION_PRIVATE = "__FreeMarkerServlet.Application__";
     public static final String KEY_JSP_TAGLIBS = "JspTaglibs";
 
     // Note these names start with dot, so they're essentially invisible from
     // a freemarker script.
     private static final String ATTR_REQUEST_MODEL = ".freemarker.Request";
     private static final String ATTR_REQUEST_PARAMETERS_MODEL = ".freemarker.RequestParameters";
     private static final String ATTR_SESSION_MODEL = ".freemarker.Session";
    
    

Deprecated:
We only keeps this attribute for backward compatibility, but actually aren't using it.
 
     private static final String ATTR_APPLICATION_MODEL = ".freemarker.Application";
    
    

Deprecated:
We only keeps this attribute for backward compatibility, but actually aren't using it.
 
     private static final String ATTR_JSP_TAGLIBS_MODEL = ".freemarker.JspTaglibs";
 
     private static final String ATTR_JETTY_CP_TAGLIB_JAR_PATTERNS
             = "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern";
     
     private static final String EXPIRATION_DATE;
 
     static {
         // Generate expiration date that is one year from now in the past
         GregorianCalendar expiration = new GregorianCalendar();
         expiration.roll(., -1);
         SimpleDateFormat httpDate =
             new SimpleDateFormat(
                 "EEE, dd MMM yyyy HH:mm:ss z",
                 ...);
          = httpDate.format(expiration.getTime());
     }
 
     // Init-param values:
     private String templatePath;
     private boolean noCache;
     private Integer bufferSize;
     private boolean exceptionOnMissingTemplate;
    
    

Deprecated:
Not used anymore; to enable/disable debug logging, just set the logging level of the logging library used by Logger.
 
     protected boolean debug;
     
     private Configuration config;
     private ObjectWrapper wrapper;
     private String contentType;
     private boolean noCharsetInContentType;
     private List/*<MetaInfTldSource>*/ metaInfTldSources;
     private List/*<String>*/ classpathTlds;
 
     private Object lazyInitFieldsLock = new Object();
     private TaglibFactory taglibFactory;
     
     private boolean objectWrapperMismatchWarnLogged;

    
Don't override this method to adjust FreeMarker settings! Override the protected methods for that, such as createConfiguration(), createTemplateLoader(String), createDefaultObjectWrapper(), etc. Also note that lot of things can be changed with init-params instead of overriding methods, so if you override settings, usually you should only override their defaults.
 
     public void init() throws ServletException {
         try {
             initialize();
         } catch (Exception e) {
             // At least Jetty doesn't log the ServletException itself, only its cause exception. Thus we add some
             // message here that (re)states the obvious.
             throw new ServletException("Error while initializing " + this.getClass().getName()
                     + " servlet; see cause exception."e);
         }
     }
     
          = createConfiguration();
         
         // Only override what's coming from the config if it was explicitly specified: 
         final String iciInitParamValue = getInitParameter(.);
         if (iciInitParamValue != null) {
             try {
                 .setSetting(.iciInitParamValue);
             } catch (Exception e) {
                 throw new InitParamValueException(.iciInitParamValuee);
             }
         }
         
         // Set FreemarkerServlet-specific defaults, except where createConfiguration() has already set them:
         }
         if (!.isLogTemplateExceptionsExplicitlySet()) {
             .setLogTemplateExceptions(false);
         }
         
          = ;
         
         // Process object_wrapper init-param out of order: 
          = createObjectWrapper();
         if (.isDebugEnabled()) {
             .debug("Using object wrapper: " + );
         }
         .setObjectWrapper();
         
         // Process TemplatePath init-param out of order:
         if ( == null && !.isTemplateLoaderExplicitlySet()) {
         }
         if ( != null) {
             try {
                 .setTemplateLoader(createTemplateLoader());
             } catch (Exception e) {
                 throw new InitParamValueException(e);
             }
         }
         
 
         // Process all other init-params:
         Enumeration initpnames = getServletConfig().getInitParameterNames();
         while (initpnames.hasMoreElements()) {
             final String name = (Stringinitpnames.nextElement();
             final String value = getInitParameter(name);
             if (name == null) {
                 throw new MalformedWebXmlException(
                         "init-param without param-name. "
                         + "Maybe the web.xml is not well-formed?");
             }
             if (value == null) {
                 throw new MalformedWebXmlException(
                         "init-param " + StringUtil.jQuote(name) + " without param-value. "
                         + "Maybe the web.xml is not well-formed?");
             }
             
             try {
                 if (name.equals()
                         || name.equals(.)
                         || name.equals()
                         || name.equals(.)) {
                     // ignore: we have already processed these
                 } else if (name.equals()) { // BC
                     if (getInitParameter(.) != null) {
                         throw new ConflictingInitParamsException(
                                 .);
                     }
                     .setDefaultEncoding(value);
                 } else if (name.equals()) { // BC
                     if (getInitParameter(.) != null) {
                         throw new ConflictingInitParamsException(
                                 .);
                     }
                     try {
                         .setTemplateUpdateDelay(Integer.parseInt(value));
                     } catch (NumberFormatException e) {
                         // Intentionally ignored
                     }
                 } else if (name.equals()) { // BC
                     if (getInitParameter(.) != null) {
                         throw new ConflictingInitParamsException(
                                 .);
                     }
     
                     if (.equals(value)) {
                         .setTemplateExceptionHandler(.);
                     } else if (.equals(value)) {
                         .setTemplateExceptionHandler(.);
                     } else if  (.equals(value)) {
                         .setTemplateExceptionHandler(.);
                     } else if  (.equals(value)) {
                         .setTemplateExceptionHandler(.);
                     } else {
                         throw new InitParamValueException(value,
                                 "Not one of the supported values.");
                     }
                 } else if (name.equals()) {
                      = StringUtil.getYesNo(value);
                 } else if (name.equals()) {
                      = new Integer(parseSize(value));
                 } else if (name.equals()) { // BC
                     if (getInitParameter() != null) {
                         throw new ConflictingInitParamsException();
                     }
                      = StringUtil.getYesNo(value);
                 } else if (name.equals()) {
                      = StringUtil.getYesNo(value);
                 } else if (name.equals()) {
                      = value;
                 } else if (name.equals()) {
                      = StringUtil.getYesNo(value);
                 } else if (name.equals()) {;
                      = parseAsMetaInfTldLocations(value);
                 } else if (name.equals()) {;
                     List newClasspathTlds = new ArrayList();
                     if ( != null) {
                         newClasspathTlds.addAll();
                     }
                     newClasspathTlds.addAll(InitParamParser.parseCommaSeparatedList(value));
                      = newClasspathTlds;
                 } else {
                     .setSetting(namevalue);
                 }
             } catch (ConflictingInitParamsException e) {
                 throw e;
             } catch (Exception e) {
                 throw new InitParamValueException(namevaluee);
             }
         } // while initpnames
         
          = true;
         int i = .toLowerCase().indexOf("charset=");
         if (i != -1) {
             char c = ' ';
             i--;
             while (i >= 0) {
                 c = .charAt(i);
                 if (!Character.isWhitespace(c)) break;
                 i--;
             }
             if (i == -1 || c == ';') {
                  = false;
             }
         }
     }
 
     private List/*<MetaInfTldSource>*/ parseAsMetaInfTldLocations(String valuethrows ParseException {
         List/*<MetaInfTldSource>*/ metaInfTldSources = null;
         
         List/*<String>*/ values = InitParamParser.parseCommaSeparatedList(value);
         for (Iterator it = values.iterator(); it.hasNext();) {
             final String itemStr = (Stringit.next();
             final MetaInfTldSource metaInfTldSource;
             if (itemStr.equals()) {
                 metaInfTldSource = .;
             } else if (itemStr.startsWith()) {
                 String itemRightSide = itemStr.substring(.length()).trim();
                 if (itemRightSide.length() == 0) {
                     metaInfTldSource = new ClasspathMetaInfTldSource(Pattern.compile(".*".));
                 } else if (itemRightSide.startsWith(":")) {
                     final String regexpStr = itemRightSide.substring(1).trim();
                     if (regexpStr.length() == 0) {
                         throw new ParseException("Empty regular expression after \""
                                 +  + ":\"", -1);
                     }
                     metaInfTldSource = new ClasspathMetaInfTldSource(Pattern.compile(regexpStr));   
                 } else {
                     throw new ParseException("Invalid \"" + 
                             + "\" value syntax: " + value, -1);
                 }
             } else if (itemStr.startsWith()) {
                 metaInfTldSource = .;
             } else {
                 throw new ParseException("Item has no recognized source type prefix: " + itemStr, -1);
             }
             if (metaInfTldSources == null) {
                 metaInfTldSources = new ArrayList();
             }
             metaInfTldSources.add(metaInfTldSource);
         }
         
         return metaInfTldSources;
     }

    
Create the template loader. The default implementation will create a ClassTemplateLoader if the template path starts with "class://", a FileTemplateLoader if the template path starts with "file://", and a WebappTemplateLoader otherwise. Also, if incompatible_improvements is 2.3.22 or higher, it will create a MultiTemplateLoader if the template path starts with "[".

Parameters:
templatePath the template path to create a loader for
Returns:
a newly created template loader
 
     protected TemplateLoader createTemplateLoader(String templatePaththrows IOException {
         return InitParamParser.createTemplateLoader(templatePathgetConfiguration(), getClass(), getServletContext());
     }
     
     public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
     {
         process(requestresponse);
     }
 
     public void doPost(
         HttpServletRequest request,
         HttpServletResponse response)
         throws ServletException, IOException
     {
         process(requestresponse);
     }
 
     private void process(
         HttpServletRequest request,
         HttpServletResponse response)
         throws ServletException, IOException
     {
         // Give chance to subclasses to perform preprocessing
         if (preprocessRequest(requestresponse)) {
             return;
         }
         
         if ( != null && !response.isCommitted()) {
             try {
                 response.setBufferSize(.intValue());
             } catch (IllegalStateException e) {
                 .debug("Can't set buffer size any more,"e);
             }
         }
 
         String templatePath = requestUrlToTemplatePath(request);
 
         if (.isDebugEnabled()) {
             .debug("Requested template " + StringUtil.jQuoteNoXSS(templatePath) + ".");
         }
 
         final Locale locale = deduceLocale(templatePathrequestresponse);
         
         final Template template;
         try {
             template = .getTemplate(templatePathlocale);
         } catch (TemplateNotFoundException e) {
             if () {
                 throw newServletExceptionWithFreeMarkerLogging(
                         "Template not found for name " + StringUtil.jQuoteNoXSS(templatePath) + "."e);
             } else {
                 if (.isDebugEnabled()) {
                     .debug("Responding HTTP 404 \"Not found\" for missing template "
                             + StringUtil.jQuoteNoXSS(templatePath) + "."e);
                 }
                 response.sendError(HttpServletResponse.SC_NOT_FOUND, "Page template not found");
                 return;
             }
         } catch (freemarker.core.ParseException e) {
             throw newServletExceptionWithFreeMarkerLogging(
                     "Parsing error with template " + StringUtil.jQuoteNoXSS(templatePath) + "."e);
         } catch (Exception e) {
             throw newServletExceptionWithFreeMarkerLogging(
                     "Unexpected error when loading template " + StringUtil.jQuoteNoXSS(templatePath) + "."e);
         }
         
         Object attrContentType = template.getCustomAttribute("content_type");
         if(attrContentType != null) {
             response.setContentType(attrContentType.toString());
         } else {
             if () {
                 response.setContentType( + "; charset=" + template.getEncoding());
             } else {
                 response.setContentType();
             }
         }
 
         setBrowserCachingPolicy(response);
 
         ServletContext servletContext = getServletContext();
         try {
             logWarnOnObjectWrapperMismatch();
             
             TemplateModel model = createModel(servletContextrequestresponse);
 
             // Give subclasses a chance to hook into preprocessing
             if (preTemplateProcess(requestresponsetemplatemodel)) {
                 try {
                     // Process the template
                     template.process(modelresponse.getWriter());
                 } finally {
                     // Give subclasses a chance to hook into postprocessing
                     postTemplateProcess(requestresponsetemplatemodel);
                 }
             }
         } catch (TemplateException e) {
             final TemplateExceptionHandler teh = .getTemplateExceptionHandler();
             // Ensure that debug handler responses aren't rolled back:
             if (teh == . || teh == .
                     || teh.getClass().getName().indexOf("Debug") != -1) {
                 response.flushBuffer();
             }
             throw newServletExceptionWithFreeMarkerLogging("Error executing FreeMarker template"e);
         }
     }
 
     private ServletException newServletExceptionWithFreeMarkerLogging(String messageThrowable causethrows ServletException {
         if (cause instanceof TemplateException) {
             // For backward compatibility, we log into the same category as Environment did when
             // log_template_exceptions was true.
             .error(messagecause);
         } else {
             .error(messagecause);
         }
 
         ServletException e = new ServletException(messagecause);
         try {
             // Prior to Servlet 2.5, the cause exception wasn't set by the above constructor.
             // If we are on 2.5+ then this will throw an exception as the cause was already set.
             e.initCause(cause);
         } catch (Exception ex) {
             // Ignored; see above
         }
         throw e;
     }
     
     private void logWarnOnObjectWrapperMismatch() {
         // Deliberately uses double check locking.
             final boolean logWarn;
             synchronized (this) {
                 logWarn = !;
                 if (logWarn) {
                      = true;
                 }
             }
             if (logWarn) {
                 .warn(
                         this.getClass().getName()
                         + ".wrapper != config.getObjectWrapper(); possibly the result of incorrect extension of "
                         + FreemarkerServlet.class.getName() + ".");
             }
         }
     }
    
    
Returns the locale used for the Configuration.getTemplate(String, Locale) call. The base implementation simply returns the locale setting of the configuration. Override this method to provide different behaviour, i.e. to use the locale indicated in the request.

Parameters:
templatePath The template path (templat name) as it will be passed to Configuration.getTemplate(String). (Not to be confused with the servlet init-param of identical name; they aren't related.)
Throws:
ServletException Can be thrown since 2.3.22, if the locale can't be deduced from the URL.
 
     protected Locale deduceLocale(String templatePath, HttpServletRequest request, HttpServletResponse response)
             throws ServletException {
         return .getLocale();
     }
 
     protected TemplateModel createModel(ObjectWrapper objectWrapper,
                                         ServletContext servletContext,
                                         final HttpServletRequest request,
                                         final HttpServletResponse responsethrows TemplateModelException {
         try {
             AllHttpScopesHashModel params = new AllHttpScopesHashModel(objectWrapperservletContextrequest);
     
             // Create hash model wrapper for servlet context (the application)
             final ServletContextHashModel servletContextModel;
             final TaglibFactory taglibFactory;
             synchronized () {
                 if (this. == null) {
                     servletContextModel = new ServletContextHashModel(thisobjectWrapper);
                     taglibFactory = createTaglibFactory(objectWrapperservletContext);
                     
                     // For backward compatibility only. We don't use these:
                     servletContext.setAttribute(servletContextModel);
                     servletContext.setAttribute(taglibFactory);
                     
                     initializeServletContext(requestresponse);
 
                     this. = taglibFactory;
                     this. = servletContextModel;
                 } else {
                     servletContextModel = this.;
                     taglibFactory = this.;
                 }
             }
             
             params.putUnlistedModel(servletContextModel);
             params.putUnlistedModel(servletContextModel);
             params.putUnlistedModel(taglibFactory);
             // Create hash model wrapper for session
             HttpSessionHashModel sessionModel;
             HttpSession session = request.getSession(false);
             if(session != null) {
                 sessionModel = (HttpSessionHashModelsession.getAttribute();
                 if (sessionModel == null || sessionModel.isOrphaned(session)) {
                     sessionModel = new HttpSessionHashModel(sessionobjectWrapper);
                     initializeSessionAndInstallModel(requestresponse
                             sessionModelsession);
                 }
             }
             else {
                 sessionModel = new HttpSessionHashModel(thisrequestresponseobjectWrapper);
             }
             params.putUnlistedModel(sessionModel);
     
             // Create hash model wrapper for request
             HttpRequestHashModel requestModel =
                 (HttpRequestHashModelrequest.getAttribute();
             if (requestModel == null || requestModel.getRequest() != request)
             {
                 requestModel = new HttpRequestHashModel(requestresponseobjectWrapper);
                 request.setAttribute(requestModel);
                 request.setAttribute(
                     ,
                     createRequestParametersHashModel(request));
             }
             params.putUnlistedModel(requestModel);
             params.putUnlistedModel(new IncludePage(requestresponse));
             params.putUnlistedModel(requestModel);
     
             // Create hash model wrapper for request parameters
             HttpRequestParametersHashModel requestParametersModel =
                 (HttpRequestParametersHashModelrequest.getAttribute(
                     );
             params.putUnlistedModel(requestParametersModel);
             return params;
         } catch (ServletException e) {
             throw new TemplateModelException(e);
         } catch (IOException e) {
             throw new TemplateModelException(e);
         }
     }

    
Called to create the TaglibFactory once per servlet context. The default implementation configures it based on the servlet-init parameters and various other environmental settings, so if you override this method, you should call super, then adjust the result.

Since:
2.3.22
 
     protected TaglibFactory createTaglibFactory(ObjectWrapper objectWrapper,
             ServletContext servletContextthrows TemplateModelException {
         TaglibFactory taglibFactory = new TaglibFactory(servletContext);
         
         taglibFactory.setObjectWrapper(objectWrapper);
         
         {
             List/*<MetaInfTldSource>*/ mergedMetaInfTldSources = new ArrayList();
 
             if ( != null) {
                 mergedMetaInfTldSources.addAll();
             }
             
             String sysPropVal = SecurityUtilities.getSystemProperty(null);
             if (sysPropVal != null) {
                 try {
                     List metaInfTldSourcesSysProp = parseAsMetaInfTldLocations(sysPropVal);
                     if (metaInfTldSourcesSysProp != null) {
                         mergedMetaInfTldSources.addAll(metaInfTldSourcesSysProp);
                     }
                 } catch (ParseException e) {
                     throw new TemplateModelException("Failed to parse system property \""
                             +  + "\""e);
                 }
             }
 
             List/*<Pattern>*/ jettyTaglibJarPatterns = null;
             try {
                 final String attrVal = (StringservletContext.getAttribute();
                 jettyTaglibJarPatterns = attrVal != null ? InitParamParser.parseCommaSeparatedPatterns(attrVal) : null;
             } catch (Exception e) {
                 .error("Failed to parse application context attribute \""
                         +  + "\" - it will be ignored"e);
             }
             if (jettyTaglibJarPatterns != null) {
                 for (Iterator/*<Pattern>*/ it = jettyTaglibJarPatterns.iterator(); it.hasNext();) {
                     Pattern pattern = (Patternit.next();
                     mergedMetaInfTldSources.add(new ClasspathMetaInfTldSource(pattern));
                 }
             }
             
             taglibFactory.setMetaInfTldSources(mergedMetaInfTldSources);
         }
         
         {
             List/*<String>*/ mergedClassPathTlds = new ArrayList();
             if ( != null) {
                 mergedClassPathTlds.addAll();
             }
             
             String sysPropVal = SecurityUtilities.getSystemProperty(null);
             if (sysPropVal != null) {
                 try {
                     List/*<String>*/ classpathTldsSysProp = InitParamParser.parseCommaSeparatedList(sysPropVal);
                     if (classpathTldsSysProp != null) {
                         mergedClassPathTlds.addAll(classpathTldsSysProp);
                     }
                 } catch (ParseException e) {
                     throw new TemplateModelException("Failed to parse system property \""
                             +  + "\""e);
                 }
             }
             
             taglibFactory.setClasspathTlds(mergedClassPathTlds);
         }
         
         return taglibFactory;        
     }

    
Creates the default of the .INIT_PARAM_CLASSPATH_TLDS init-param; if this init-param is specified, it will be appended after the default, not replace it.

The implementation in FreemarkerServlet returns TaglibFactory.DEFAULT_CLASSPATH_TLDS.

Returns:
A List of String-s; not null.
Since:
2.3.22
 
     protected List/*<MetaInfTldSource>*/ createDefaultClassPathTlds() {
         return .;
     }

    
Creates the default of the .INIT_PARAM_META_INF_TLD_LOCATIONS init-param; if this init-param is specified, it will completelly replace the default value.

The implementation in FreemarkerServlet returns TaglibFactory.DEFAULT_META_INF_TLD_SOURCES.

Returns:
A List of MetaInfTldSource-s; not null.
Since:
2.3.22
 
     protected List/*<MetaInfTldSource>*/ createDefaultMetaInfTldSources() {
     }
     
     void initializeSessionAndInstallModel(HttpServletRequest request,
             HttpServletResponse responseHttpSessionHashModel sessionModel
             HttpSession session)
             throws ServletException, IOException
     {
         session.setAttribute(sessionModel);
         initializeSession(requestresponse);
     }

    
Maps the request URL to a template path (template name) that is passed to Configuration.getTemplate(String, Locale). You can override it (i.e. to provide advanced rewriting capabilities), but you are strongly encouraged to call the overridden method first, then only modify its return value.

Parameters:
request The currently processed HTTP request
Returns:
The template path (template name); can't be null. This is what's passed to Configuration.getTemplate(String) later. (Not to be confused with the templatePath servlet init-param of identical name; that basically specifies the "virtual file system" to which this will be relative to.)
Throws:
ServletException Can be thrown since 2.3.22, if the template path can't be deduced from the URL.
    protected String requestUrlToTemplatePath(HttpServletRequest requestthrows ServletException
    {
        // First, see if it's an included request
        String includeServletPath  = (Stringrequest.getAttribute("javax.servlet.include.servlet_path");
        if(includeServletPath != null)
        {
            // Try path info; only if that's null (servlet is mapped to an
            // URL extension instead of to prefix) use servlet path.
            String includePathInfo = (Stringrequest.getAttribute("javax.servlet.include.path_info");
            return includePathInfo == null ? includeServletPath : includePathInfo;
        } 
        // Seems that the servlet was not called as the result of a 
        // RequestDispatcher.include(...). Try pathInfo then servletPath again,
        // only now directly on the request object:
        String path = request.getPathInfo();
        if (path != nullreturn path;
        path = request.getServletPath();
        if (path != nullreturn path;
        // Seems that it's a servlet mapped with prefix, and there was no extra path info.
        return "";
    }

    
Called as the first step in request processing, before the templating mechanism is put to work. By default does nothing and returns false. This method is typically overridden to manage serving of non-template resources (i.e. images) that reside in the template directory.

Parameters:
request the HTTP request
response the HTTP response
Returns:
true to indicate this method has processed the request entirely, and that the further request processing should not take place.
    protected boolean preprocessRequest(
        HttpServletRequest request,
        HttpServletResponse response)
            throws ServletException, IOException {
        return false;
    }

    
Creates the FreeMarker Configuration singleton and (when overidden) maybe sets its defaults. Servlet init-params will be applied later, and thus can overwrite the settings specified here.

By overriding this method you can set your preferred Configuration setting defaults, as only the settings for which an init-param was specified will be overwritten later. (Note that FreemarkerServlet also has its own defaults for a few settings, but since 2.3.22, the servlet detects if those settings were already set here and then it won't overwrite them.)

The default implementation simply creates a new instance with Configuration.Configuration() and returns it.

    protected Configuration createConfiguration() {
        // We can only set incompatible_improvements later, so ignore the deprecation warning here.
        return new Configuration();
    }
    
    
Sets the defaults of the configuration that are specific to the FreemarkerServlet subclass. This is called after the common (wired in) FreemarkerServlet setting defaults was set, also the
    protected void setConfigurationDefaults() {
        // do nothing
    }
    
    
Called from init() to create the ObjectWrapper; to customzie this aspect, in most cases you should override createDefaultObjectWrapper() instead. Overriding this method is necessary when you want to customize how the ObjectWrapper is created from the init-param values, or you want to do some post-processing (like checking) on the created ObjectWrapper. To customize init-param interpretation, call getInitParameter(String) with Configurable.OBJECT_WRAPPER_KEY as argument, and see if it returns a value that you want to interpret yourself. If was null or you don't want to interpret the value, fall back to the super method.

The default implementation interprets the object_wrapper servlet init-param with calling Configurable.setSetting(String, String) (see valid values there), or if there's no such servlet init-param, then it calls createDefaultObjectWrapper().

Returns:
The ObjectWrapper that will be used for adapting request, session, and servlet context attributes to TemplateModel-s, and also as the object wrapper setting of Configuration.
    protected ObjectWrapper createObjectWrapper() {
        String wrapper = getServletConfig().getInitParameter();
        if (wrapper != null) { // BC
            if (getInitParameter(.) != null) {
                throw new RuntimeException("Conflicting init-params: "
                        + . + " and "
                        + );
            }
            if (.equals(wrapper)) {
                return .;
            }
            if(.equals(wrapper)) {
                return .;
            }
            if(.equals(wrapper)) {
                // Avoiding compile-time dependency on Jython package
                try {
                    return (ObjectWrapper) Class.forName("freemarker.ext.jython.JythonWrapper")
                            .newInstance();
                } catch (InstantiationException e) {
                    throw new InstantiationError(e.getMessage());
                } catch (IllegalAccessException e) {
                    throw new IllegalAccessError(e.getMessage());
                } catch (ClassNotFoundException e) {
                    throw new NoClassDefFoundError(e.getMessage());
                }
            }
            return createDefaultObjectWrapper();
        } else {
            wrapper = getInitParameter(.);
            if (wrapper == null) {
                if (!.isObjectWrapperExplicitlySet()) {
                    return createDefaultObjectWrapper();
                } else {
                    return .getObjectWrapper();
                }
            } else {
                try {
                    .setSetting(.wrapper);
                } catch (TemplateException e) {
                    throw new RuntimeException("Failed to set " + .e);
                }
                return .getObjectWrapper();
            }
        }
    }

    
Override this to specify what the default ObjectWrapper will be when the object_wrapper Servlet init-param wasn't specified. Note that this is called by createConfiguration(), and so if that was also overidden but improperly then this method might won't be ever called. Also note that if you set the object_wrapper in createConfiguration(), then this won't be called, since then that has already specified the default.

The default implementation calls Configuration.getDefaultObjectWrapper(freemarker.template.Version). You should also pass in the version paramter when creating an ObjectWrapper that supports that. You can get the version by calling getConfiguration() and then Configuration.getIncompatibleImprovements().

Since:
2.3.22
        return Configuration.getDefaultObjectWrapper(.getIncompatibleImprovements());
    }
    
    
Should be final; don't override it. Override createObjectWrapper() instead.
    // [2.4] Make it final
    protected ObjectWrapper getObjectWrapper() {
        return ;
    }
    
    
The value of the TemplatePath init-param. null if the template_loader setting was set in a custom createConfiguration().

Deprecated:
Not called by FreeMarker code, and there's no point to override this (unless to cause confusion).
    protected final String getTemplatePath() {
        return ;
    }
    
    protected HttpRequestParametersHashModel createRequestParametersHashModel(HttpServletRequest request) {
        return new HttpRequestParametersHashModel(request);
    }

    
Called when servlet detects in a request processing that application-global (that is, ServletContext-specific) attributes are not yet set. This is a generic hook you might use in subclasses to perform a specific action on first request in the context. By default it does nothing.

Parameters:
request the actual HTTP request
response the actual HTTP response
    protected void initializeServletContext(
        HttpServletRequest request,
        HttpServletResponse response)
            throws ServletException, IOException {
    }

    
Called when servlet detects in a request processing that session-global (that is, HttpSession-specific) attributes are not yet set. This is a generic hook you might use in subclasses to perform a specific action on first request in the session. By default it does nothing. It is only invoked on newly created sessions; it's not invoked when a replicated session is reinstantiated in another servlet container.

Parameters:
request the actual HTTP request
response the actual HTTP response
    protected void initializeSession(
        HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException
    {
    }

    
Called before the execution is passed to template.process(). This is a generic hook you might use in subclasses to perform a specific action before the template is processed. By default does nothing. A typical action to perform here is to inject application-specific objects into the model root

Example: Expose the Serlvet context path as "baseDir" for all templates:

    ((SimpleHash) data).put("baseDir", request.getContextPath() + "/");
    return true;

Parameters:
request the actual HTTP request
response the actual HTTP response
template the template that will get executed
data the data that will be passed to the template. By default this will be an AllHttpScopesHashModel (which is a freemarker.template.SimpleHash subclass). Thus, you can add new variables to the data-model with the freemarker.template.SimpleHash.put(String, Object) subclass) method.
Returns:
true to process the template, false to suppress template processing.
    protected boolean preTemplateProcess(
        HttpServletRequest request,
        HttpServletResponse response,
        Template template,
        TemplateModel data)
        throws ServletException, IOException
    {
        return true;
    }

    
Called after the execution returns from template.process(). This is a generic hook you might use in subclasses to perform a specific action after the template is processed. It will be invoked even if the template processing throws an exception. By default does nothing.

Parameters:
request the actual HTTP request
response the actual HTTP response
template the template that was executed
data the data that was passed to the template
    protected void postTemplateProcess(
        HttpServletRequest request,
        HttpServletResponse response,
        Template template,
        TemplateModel data)
        throws ServletException, IOException
    {
    }
    
    
Returns the freemarker.template.Configuration object used by this servlet. Please don't forget that freemarker.template.Configuration is not thread-safe when you modify it.
    protected Configuration getConfiguration() {
        return ;
    }

    
If the parameter "nocache" was set to true, generate a set of headers that will advise the HTTP client not to cache the returned page.
    private void setBrowserCachingPolicy(HttpServletResponse res)
    {
        if ()
        {
            // HTTP/1.1 + IE extensions
            res.setHeader("Cache-Control""no-store, no-cache, must-revalidate, "
                    + "post-check=0, pre-check=0");
            // HTTP/1.0
            res.setHeader("Pragma""no-cache");
            // Last resort for those that ignore all of the above
            res.setHeader("Expires");
        }
    }
    
    private int parseSize(String valuethrows ParseException {
        int lastDigitIdx;
        for (lastDigitIdx = value.length() - 1; lastDigitIdx >= 0; lastDigitIdx--) {
            char c = value.charAt(lastDigitIdx);
            if (c >= '0' && c <= '9') {
                break;
            }
        }
        
        final int n = Integer.parseInt(value.substring(0, lastDigitIdx + 1).trim());
        
        final String unitStr = value.substring(lastDigitIdx + 1).trim().toUpperCase();
        final int unit;
        if (unitStr.length() == 0 || unitStr.equals("B")) {
            unit = 1;
        } else if (unitStr.equals("K") || unitStr.equals("KB") || unitStr.equals("KIB")) {
            unit = 1024;
        } else if (unitStr.equals("M") || unitStr.equals("MB") || unitStr.equals("MIB")) {
            unit = 1024 * 1024;
        } else {
            throw new ParseException("Unknown unit: " + unitStrlastDigitIdx + 1);
        }
        
        long size = (longn * unit;
        if (size < 0) {
            throw new IllegalArgumentException("Buffer size can't be negative");
        }
        if (size > .) {
            throw new IllegalArgumentException("Buffer size can't bigger than " + .);
        }
        return (intsize;
    }
    private static class InitParamValueException extends Exception {
        
        InitParamValueException(String initParamNameString initParamValueThrowable casue) {
            super("Failed to set the " + StringUtil.jQuote(initParamName) + " servlet init-param to "
                    + StringUtil.jQuote(initParamValue) + "; see cause exception.",
                    casue);
        }
        public InitParamValueException(String initParamNameString initParamValueString cause) {
            super("Failed to set the " + StringUtil.jQuote(initParamName) + " servlet init-param to "
                    + StringUtil.jQuote(initParamValue) + ": " + cause);
        }
        
    }
    
    private static class ConflictingInitParamsException extends Exception {
        
        ConflictingInitParamsException(String recommendedNameString otherName) {
            super("Conflicting servlet init-params: "
                    + StringUtil.jQuote(recommendedName) + " and " + StringUtil.jQuote(otherName)
                    + ". Only use " + StringUtil.jQuote(recommendedName) + ".");
        }
    }
    private static class MalformedWebXmlException extends Exception {
        MalformedWebXmlException(String message) {
            super(message);
        }
        
    }