Class FreemarkerServlet
- All Implemented Interfaces:
jakarta.servlet.Servlet,jakarta.servlet.ServletConfig,Serializable
<url-pattern>*.ftl<url-pattern>). See web.xml example (and more) in the FreeMarker Manual!
Note that this is for the legacy "javax" Servlet/JSP API; for Jakarta (that is, in modern Servlet containers), use
freemarker.ext.jakarta.servlet.FreemarkerServlet instead (since 2.3.33).
Main features
- It makes all request, request parameters, session, and servlet context attributes available to templates through
Request,RequestParameters,Session, andApplicationvariables. - The scope variables are also available via automatic scope discovery. That is, writing
Application.attrName,Session.attrName,Request.attrNameis not mandatory; it's enough to writeattrName, and if no such variable was created in the template, it will search the variable inRequest, and then inSession, and finally inApplication. - It creates a variable with name
JspTaglibsthat 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_pageallows you to include the output of another servlet resource from your servlet container, just as if you usedServletRequest.getRequestDispatcher(path).include():<@include_page path="/myWebapp/somePage.jsp"/>. You can also pass parameters to the newly included page by passing a hash namedparams:<@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 theinherit_paramsparameter:<@include_page path="/myWebapp/somePage.jsp" params={lang: "en", q="5"} inherit_params=false/>.
Supported init-param-s
- "TemplatePath": Specifies the location of the template files. By default,
this is interpreted as a
ServletContextresource path, which practically means a web application directory relative path, or aWEB-INF/lib/*.jar/META-INF/resources-relative path (note that this last haven't always worked before FreeMarker 2.3.23).
Alternatively, you can prepend it withfile://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 withclasspath:, like inclasspath: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.
Ifincompatible_improvementsis 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 aMultiTemplateLoader. Note again that ifincompatible_improvementsisn'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 theTemplateLoadercreated. For example,/templates?settings(attemptFileAccess=false, URLConnectionUsesCaches=true)callsWebappTemplateLoader.setAttemptFileAccess(boolean)andWebappTemplateLoader.setURLConnectionUsesCaches(Boolean)to tune theWebappTemplateLoader. For backward compatibility (not recommended!), you can use theclass://prefix, like inclass://com/example/templatesformat, which is similar toclasspath:, except that it uses the defining class loader of this servlet's class. This can cause template-not-found errors, if that class (infreemarer.jarusually) is not local to the web application, while the templates are.
The default value isclass://(that is, the root of the class hierarchy), which is not recommended anymore, and should be overwritten with the "TemplatePath" init-param. - "NoCache": If set to
true, generates headers in the response that advise the HTTP client not to cache the returned page. Iffalse, the HTTP response is not modified for this purpose. The default isfalse. - "ContentType": The Content-type HTTP header value used in the HTTP responses
when nothing else specifies the MIME type. The things that may specify the MIME type (and hence this init-param is
ignored), starting with the highest precedence, are:
- If the "OverrideResponseContentType" init-param is "never" (the
default is "always"), then the value of
ServletResponse.getContentType()is used if that's non-null. - The template's
content_typecustom attribute, usually specified via theattributesparameter of the<#ftl>directive. This is a legacy feature, deprecated by theOutputFormatmechanism. - The output format of the template, if that has non-
nullMIME-type (OutputFormat.getMimeType()). When a template has no output format specified,UndefinedOutputFormatis used, which hasnullMIME-type. (The output format of a template is deduced fromConfigurationsettings, or can be specified directly in the template, like<#ftl outputFormat="HTML">. See the FreeMarker Manual for more about the output format mechanism. Note that setting an output format may turns on auto-escaping, so it's not just about MIME types.) - If the "OverrideResponseContentType" init-param is not "always"
(the default is "always"), then the value of
ServletResponse.getContentType()is used if that's non-null.
"text/html". If and only if the "ResponseCharacterEncoding" init-param is set to "legacy" (which is the default of it), the content type may include the charset (as in"text/html; charset=utf-8"), in which case that specifies the actual charset of the output. If the the "ResponseCharacterEncoding" init-param is not set to "legacy", then specifying the charset in the "ContentType" init-param is not allowed, and will cause servlet initialization error. - If the "OverrideResponseContentType" init-param is "never" (the
default is "always"), then the value of
- "OverrideResponseContentType" (since 2.3.24): Specifies when we should
override the
contentTypethat might be already set (i.e., non-null) in theHttpServletResponse. The default is "always", which means that we always set the content type. Another possible value is "never", which means that we don't set the content type in the response, unlessServletResponse.getContentType()isnull. The third possible value is "whenTemplateHasMimeType", which means that we only set the content type if either the template has an associatedOutputFormatwith non-nullOutputFormat.getMimeType(), or it has a custom attribute with namecontent_type, orServletResponse.getContentType()isnull. Setting this init-param allows you to specify the content type before forwarding toFreemarkerServlet. - "OverrideResponseLocale" (since 2.3.24): Specifies if we should override
the template
localethat might be already set (i.e., non-null) in theHttpServletRequest. The default is "always", which means that we always deduce the templatelocaleby invokingdeduceLocale(String, HttpServletRequest, HttpServletResponse). Another possible value is "never", which means that we don't deduce the templatelocale, unlessServletRequest.getLocale()isnull. - "ResponseCharacterEncoding" (since 2.3.24): Specifies how the
HttpServletResponse"character encoding" (as inServletResponse.setCharacterEncoding(String)) will be deduced. The possible modes are:- "legacy": This is the default for backward compatibility; in new applications, use
"fromTemplate" (or some of the other options) instead. "legacy"
will use the charset of the template file to set the charset of the servlet response. Except, if the
"ContentType" init-param contains a charset, it will use that instead. A quirk of this legacy
mode is that it's not aware of the
Configurable.getOutputEncoding()FreeMarker setting, and thus never reads or writes it (though very few applications utilize that setting anyway). Also, it sets the charset of the servlet response by adding it to the response content type via callingServletResponse.setContentType(String)(as that was the only way before Servlet 2.4), not via the more modernServletResponse.setCharacterEncoding(String)method. Note that the charset of a template usually comes fromConfiguration.getDefaultEncoding()(i.e., from thedefault_encodingFreeMarker setting), occasionally fromConfiguration.getEncoding(Locale)(when FreeMarker was configured to use different charsets depending on the locale) or even more rarely fromConfiguration.getTemplateConfigurations()(when FreeMarker was configured to use a specific charset for certain templates). - "fromTemplate": This should be used in most applications, but it's not the default for
backward compatibility. It reads the
Configurable.getOutputEncoding()setting of the template (note that the template usually just inherits that from theConfiguration), and if that's not set, then reads the source charset of the template, just like "legacy". Then it passes the charset acquired this way toServletResponse.setCharacterEncoding(String)andEnvironment.setOutputEncoding(String). (It doesn't call the legacyServletResponse.setContentType(String)API to set the charset.) (Note that if the template has acontent_typetemplate attribute (which is deprecated) that specifies a charset, it will be used as the output charset of that template.) - "doNotSet":
FreemarkerServletwill not set theHttpServletResponse"character encoding". It will still callEnvironment.setOutputEncoding(String), so that the running template will be aware of the charset used for the output. - "force " + charset name, for example
force UTF-8: The output charset will be the one specified after "force" + space, regardless of everything. The charset specified this way is passed toServletResponse.setCharacterEncoding(String)andEnvironment.setOutputEncoding(String). If the charset name is not recognized by Java, the servlet initialization will fail.
- "legacy": This is the default for backward compatibility; in new applications, use
"fromTemplate" (or some of the other options) instead. "legacy"
will use the charset of the template file to set the charset of the servlet response. Except, if the
"ContentType" init-param contains a charset, it will use that instead. A quirk of this legacy
mode is that it's not aware of the
- "BufferSize": 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 toServletResponse.setBufferSize(int). If theHttpServletResponsestate 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 byFreemarkerServletin the HTTP response, which usually means that the default buffer size of the servlet container will be used. - "ExceptionOnMissingTemplate" (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. Iftrue(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! - "MetaInfTldSources" (since 2.3.22): Comma separated list of items, each
is either "webInfPerLibJars", or "classpath"
optionally followed by colon and a regular expression, or "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.) SeeTaglibFactory.setMetaInfTldSources(List)for more information. Defaults to a list that contains "webInfPerLibJars" only (can be overridden withcreateDefaultMetaInfTldSources()). Note that this can be also specified with the "org.freemarker.jsp.metaInfTldSources" 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, "clear" comes handy, as it will remove all previous list items. (An intended usage of the system property is setting it toclear, classpathin the Eclipse run configuration if you are running the application without putting the dependency jar-s intoWEB-INF/lib.) Also, note that furtherclasspath:<pattern>items are added automatically at the end of this list based on Jetty's"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern"servlet context attribute. - "ClasspathTlds" (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 withcreateDefaultClassPathTlds()). Note that this can also be specified with the "org.freemarker.jsp.classpathTlds" 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 atConfiguration.setSetting(String, String), such asobject_wrapper. - Any other init-params will be interpreted as
Configuration-level FreeMarker setting. See the possible names and values atConfiguration.setSetting(String, String). Note that these init-param names are starting with lower-case letter (upper-case init-params are used for FreemarkerSerlvet settings).
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
ServletExceptionto 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 "ExceptionOnMissingTemplate" init-param to
true(recommended), it will instead log the problem with error level, then the servlet throwsServletExceptionto 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
ServletExceptionto the servlet container (with the proper cause exception). - If the template throws exception during its execution, and the value of the
template_exception_handlerinit-param isrethrow(recommended), it will log it with error level and then the servlet throwsServletExceptionto the servlet container (with the proper cause exception). But beware, the default value of thetemplate_exception_handlerinit-param ishtml_debug, which is for development only! Set it torethrowfor production. Thehtml_debug(anddebug) 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.
- See Also:
- Serialized Form
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected booleanDeprecated.static StringInit-param name - see theFreemarkerServletclass documentation about the init-params.static StringInit-param name - see theFreemarkerServletclass documentation about the init-params.static StringInit-param name - see theFreemarkerServletclass documentation about the init-params.static StringInit-param name - see theFreemarkerServletclass documentation about the init-params.static StringInit-param name - see theFreemarkerServletclass documentation about the init-params.static StringInit-param name - see theFreemarkerServletclass documentation about the init-params.static StringInit-param name - see theFreemarkerServletclass documentation about the init-params.static StringInit-param name - see theFreemarkerServletclass documentation about the init-params.static StringInit-param name - see theFreemarkerServletclass documentation about the init-params.static StringInit-param name - see theFreemarkerServletclass documentation about the init-params.static Stringstatic Stringstatic Stringstatic Stringstatic Stringstatic Stringstatic Stringstatic Stringstatic Stringstatic Stringstatic Stringstatic Stringstatic Stringstatic Stringstatic Stringstatic StringUsed as part of the value of the "MetaInfTldSources" init-param.static StringUsed as part of the value of the "MetaInfTldSources" init-param.static StringUsed as part of the value of the "MetaInfTldSources" init-param.static longstatic StringWhen set, the items defined in it will be added after those coming from the "ClasspathTlds" init-param.static StringWhen set, the items defined in it will be added after those coming from the "MetaInfTldSources" init-param. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected ConfigurationCreates the FreeMarkerConfigurationsingleton and (when overidden) maybe sets its defaults.protected ListCreates the default of the "ClasspathTlds" init-param; if this init-param is specified, it will be appended after the default, not replace it.protected ListCreates the default of the "MetaInfTldSources" init-param; if this init-param is specified, it will completelly replace the default value.protected ObjectWrapperOverride this to specify what the defaultObjectWrapperwill be when theobject_wrapperServlet init-param wasn't specified.protected TemplateModelcreateModel(ObjectWrapper objectWrapper, jakarta.servlet.ServletContext servletContext, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response)protected ObjectWrapperCalled frominit()to create theObjectWrapper; to customzie this aspect, in most cases you should overridecreateDefaultObjectWrapper()instead.protected HttpRequestParametersHashModelcreateRequestParametersHashModel(jakarta.servlet.http.HttpServletRequest request)protected TaglibFactorycreateTaglibFactory(ObjectWrapper objectWrapper, jakarta.servlet.ServletContext servletContext)Called to create theTaglibFactoryonce per servlet context.protected TemplateLoadercreateTemplateLoader(String templatePath)Create the template loader.protected LocalededuceLocale(String templatePath, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response)Returns the locale used for theConfiguration.getTemplate(String, Locale)call (as far as the "OverrideResponseLocale" Servlet init-param allows that).voiddoGet(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response)voiddoPost(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response)protected ConfigurationReturns theConfigurationobject used by this servlet.protected StringReturns the default value of the "OverrideResponseContentType" Servlet init-param.protected ObjectWrapperShould be final; don't override it.protected StringDeprecated.Not called by FreeMarker code, and there's no point to override this (unless to cause confusion).voidinit()Don't override this method to adjust FreeMarker settings! Override the protected methods for that, such ascreateConfiguration(),createTemplateLoader(String),createDefaultObjectWrapper(), etc.protected voidinitializeServletContext(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response)Called when servlet detects in a request processing that application-global (that is, ServletContext-specific) attributes are not yet set.protected voidinitializeSession(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response)Called when servlet detects in a request processing that session-global (that is, HttpSession-specific) attributes are not yet set.protected voidpostTemplateProcess(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Template template, TemplateModel data)Called after the execution returns fromTemplate.process(Object, java.io.Writer).protected booleanpreprocessRequest(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response)Called as the first step in request processing, before the templating mechanism is put to work.protected booleanpreTemplateProcess(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Template template, TemplateModel model)Called before the execution is passed toTemplate.process(Object, java.io.Writer).protected voidprocessEnvironment(Environment env, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response)This is the method that actually executes the template.protected StringrequestUrlToTemplatePath(jakarta.servlet.http.HttpServletRequest request)Maps the request URL to a template path (template name) that is passed toConfiguration.getTemplate(String, Locale).protected voidSets the defaults of the configuration that are specific to theFreemarkerServletsubclass.Methods inherited from class jakarta.servlet.http.HttpServlet
doDelete, doHead, doOptions, doPut, doTrace, getLastModified, service, serviceMethods inherited from class jakarta.servlet.GenericServlet
destroy, getInitParameter, getInitParameterNames, getServletConfig, getServletContext, getServletInfo, getServletName, init, log, log
-
Field Details
-
serialVersionUID
public static final long serialVersionUID- See Also:
- Constant Field Values
-
INIT_PARAM_TEMPLATE_PATH
Init-param name - see theFreemarkerServletclass 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
- See Also:
- Constant Field Values
-
INIT_PARAM_NO_CACHE
Init-param name - see theFreemarkerServletclass 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
- See Also:
- Constant Field Values
-
INIT_PARAM_CONTENT_TYPE
Init-param name - see theFreemarkerServletclass 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
- See Also:
- Constant Field Values
-
INIT_PARAM_OVERRIDE_RESPONSE_CONTENT_TYPE
Init-param name - see theFreemarkerServletclass documentation about the init-params.- Since:
- 2.3.24
- See Also:
- Constant Field Values
-
INIT_PARAM_RESPONSE_CHARACTER_ENCODING
Init-param name - see theFreemarkerServletclass documentation about the init-params.- Since:
- 2.3.24
- See Also:
- Constant Field Values
-
INIT_PARAM_OVERRIDE_RESPONSE_LOCALE
Init-param name - see theFreemarkerServletclass documentation about the init-params.- Since:
- 2.3.24
- See Also:
- Constant Field Values
-
INIT_PARAM_BUFFER_SIZE
Init-param name - see theFreemarkerServletclass documentation about the init-params.- Since:
- 2.3.22
- See Also:
- Constant Field Values
-
INIT_PARAM_META_INF_TLD_LOCATIONS
Init-param name - see theFreemarkerServletclass documentation about the init-params.- Since:
- 2.3.22
- See Also:
- Constant Field Values
-
INIT_PARAM_EXCEPTION_ON_MISSING_TEMPLATE
Init-param name - see theFreemarkerServletclass documentation about the init-params.- Since:
- 2.3.22
- See Also:
- Constant Field Values
-
INIT_PARAM_CLASSPATH_TLDS
Init-param name - see theFreemarkerServletclass documentation about the init-params.- Since:
- 2.3.22
- See Also:
- Constant Field Values
-
INIT_PARAM_VALUE_NEVER
- See Also:
- Constant Field Values
-
INIT_PARAM_VALUE_ALWAYS
- See Also:
- Constant Field Values
-
INIT_PARAM_VALUE_WHEN_TEMPLATE_HAS_MIME_TYPE
- See Also:
- Constant Field Values
-
INIT_PARAM_VALUE_FROM_TEMPLATE
- See Also:
- Constant Field Values
-
INIT_PARAM_VALUE_LEGACY
- See Also:
- Constant Field Values
-
INIT_PARAM_VALUE_DO_NOT_SET
- See Also:
- Constant Field Values
-
INIT_PARAM_VALUE_FORCE_PREFIX
- See Also:
- Constant Field Values
-
SYSTEM_PROPERTY_META_INF_TLD_SOURCES
When set, the items defined in it will be added after those coming from the "MetaInfTldSources" init-param. The value syntax is the same as of the init-param. Note that "clear" can be used to re-start the list, rather than continue it.- Since:
- 2.3.22
- See Also:
- Constant Field Values
-
SYSTEM_PROPERTY_CLASSPATH_TLDS
When set, the items defined in it will be added after those coming from the "ClasspathTlds" init-param. The value syntax is the same as of the init-param.- Since:
- 2.3.22
- See Also:
- Constant Field Values
-
META_INF_TLD_LOCATION_WEB_INF_PER_LIB_JARS
Used as part of the value of the "MetaInfTldSources" init-param.- Since:
- 2.3.22
- See Also:
- Constant Field Values
-
META_INF_TLD_LOCATION_CLASSPATH
Used as part of the value of the "MetaInfTldSources" init-param.- Since:
- 2.3.22
- See Also:
- Constant Field Values
-
META_INF_TLD_LOCATION_CLEAR
Used as part of the value of the "MetaInfTldSources" init-param.- Since:
- 2.3.22
- See Also:
- Constant Field Values
-
KEY_REQUEST
- See Also:
- Constant Field Values
-
KEY_INCLUDE
- See Also:
- Constant Field Values
-
KEY_REQUEST_PRIVATE
- See Also:
- Constant Field Values
-
KEY_REQUEST_PARAMETERS
- See Also:
- Constant Field Values
-
KEY_SESSION
- See Also:
- Constant Field Values
-
KEY_APPLICATION
- See Also:
- Constant Field Values
-
KEY_APPLICATION_PRIVATE
- See Also:
- Constant Field Values
-
KEY_JSP_TAGLIBS
- See Also:
- Constant Field Values
-
debug
Deprecated.Not used anymore; to enable/disable debug logging, just set the logging level of the logging library used byLogger.
-
-
Constructor Details
-
FreemarkerServlet
public FreemarkerServlet()
-
-
Method Details
-
init
public void init() throws jakarta.servlet.ServletExceptionDon't override this method to adjust FreeMarker settings! Override the protected methods for that, such ascreateConfiguration(),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.- Overrides:
initin classjakarta.servlet.GenericServlet- Throws:
jakarta.servlet.ServletException
-
createTemplateLoader
Create the template loader. The default implementation will create aClassTemplateLoaderif the template path starts with"class://", aFileTemplateLoaderif the template path starts with"file://", and aWebappTemplateLoaderotherwise. Also, ifincompatible_improvementsis 2.3.22 or higher, it will create aMultiTemplateLoaderif the template path starts with"[".- Parameters:
templatePath- the template path to create a loader for- Returns:
- a newly created template loader
- Throws:
IOException
-
doGet
public void doGet(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws jakarta.servlet.ServletException, IOException- Overrides:
doGetin classjakarta.servlet.http.HttpServlet- Throws:
jakarta.servlet.ServletExceptionIOException
-
doPost
public void doPost(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws jakarta.servlet.ServletException, IOException- Overrides:
doPostin classjakarta.servlet.http.HttpServlet- Throws:
jakarta.servlet.ServletExceptionIOException
-
processEnvironment
protected void processEnvironment(Environment env, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws TemplateException, IOExceptionThis is the method that actually executes the template. The original implementation coming fromFreemarkerServletsimply callsEnvironment.process(). Overriding this method allows you to prepare theEnvironmentbefore the execution, or extract information from theEnvironmentafter the execution. It also allows you to capture exceptions throw by the template.- Parameters:
env- TheEnvironmentobject already set up to execute the template. You only have to callEnvironment.process()and the output will be produced by the template.- Throws:
TemplateExceptionIOException- Since:
- 2.3.24
-
deduceLocale
protected Locale deduceLocale(String templatePath, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws jakarta.servlet.ServletExceptionReturns the locale used for theConfiguration.getTemplate(String, Locale)call (as far as the "OverrideResponseLocale" Servlet init-param allows that). The base implementation inFreemarkerServletsimply returns thelocalesetting of the configuration. Override this method to provide different behavior, for example, to use the locale indicated in the HTTP request.- Parameters:
templatePath- The template path (template name) as it will be passed toConfiguration.getTemplate(String). (Not to be confused with the servlet init-param of identical name; they aren't related.)- Throws:
jakarta.servlet.ServletException- Can be thrown since 2.3.22, if the locale can't be deduced from the URL.
-
createModel
protected TemplateModel createModel(ObjectWrapper objectWrapper, jakarta.servlet.ServletContext servletContext, jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws TemplateModelException- Throws:
TemplateModelException
-
createTaglibFactory
protected TaglibFactory createTaglibFactory(ObjectWrapper objectWrapper, jakarta.servlet.ServletContext servletContext) throws TemplateModelExceptionCalled to create theTaglibFactoryonce 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.- Throws:
TemplateModelException- Since:
- 2.3.22
-
createDefaultClassPathTlds
Creates the default of the "ClasspathTlds" init-param; if this init-param is specified, it will be appended after the default, not replace it.The implementation in
FreemarkerServletreturnsTaglibFactory.DEFAULT_CLASSPATH_TLDS. -
createDefaultMetaInfTldSources
Creates the default of the "MetaInfTldSources" init-param; if this init-param is specified, it will completelly replace the default value.The implementation in
FreemarkerServletreturnsTaglibFactory.DEFAULT_META_INF_TLD_SOURCES.- Returns:
- A
ListofTaglibFactory.MetaInfTldSource-s; notnull. - Since:
- 2.3.22
-
requestUrlToTemplatePath
protected String requestUrlToTemplatePath(jakarta.servlet.http.HttpServletRequest request) throws jakarta.servlet.ServletExceptionMaps the request URL to a template path (template name) that is passed toConfiguration.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 toConfiguration.getTemplate(String)later. (Not to be confused with thetemplatePathservlet init-param of identical name; that basically specifies the "virtual file system" to which this will be relative to.) - Throws:
jakarta.servlet.ServletException- Can be thrown since 2.3.22, if the template path can't be deduced from the URL.
-
preprocessRequest
protected boolean preprocessRequest(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws jakarta.servlet.ServletException, IOExceptionCalled 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 requestresponse- the HTTP response- Returns:
- true to indicate this method has processed the request entirely, and that the further request processing should not take place.
- Throws:
jakarta.servlet.ServletExceptionIOException
-
createConfiguration
Creates the FreeMarkerConfigurationsingleton 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
Configurationsetting defaults, as only the settings for which an init-param was specified will be overwritten later. (Note thatFreemarkerServletalso 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()and returns it. -
setConfigurationDefaults
protected void setConfigurationDefaults()Sets the defaults of the configuration that are specific to theFreemarkerServletsubclass. This is called after the common (wired in)FreemarkerServletsetting defaults was set, also the -
createObjectWrapper
Called frominit()to create theObjectWrapper; to customzie this aspect, in most cases you should overridecreateDefaultObjectWrapper()instead. Overriding this method is necessary when you want to customize how theObjectWrapperis created from the init-param values, or you want to do some post-processing (like checking) on the createdObjectWrapper. To customize init-param interpretation, callGenericServlet.getInitParameter(String)withConfigurable.OBJECT_WRAPPER_KEYas argument, and see if it returns a value that you want to interpret yourself. If wasnullor you don't want to interpret the value, fall back to the super method.The default implementation interprets the
object_wrapperservlet init-param with callingConfigurable.setSetting(String, String)(see valid values there), or if there's no such servlet init-param, then it callscreateDefaultObjectWrapper().- Returns:
- The
ObjectWrapperthat will be used for adapting request, session, and servlet context attributes toTemplateModel-s, and also as the object wrapper setting ofConfiguration.
-
createDefaultObjectWrapper
Override this to specify what the defaultObjectWrapperwill be when theobject_wrapperServlet init-param wasn't specified. Note that this is called bycreateConfiguration(), and so if that was also overidden but improperly then this method might won't be ever called. Also note that if you set theobject_wrapperincreateConfiguration(), 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 anObjectWrapperthat supports that. You can get the version by callinggetConfiguration()and thenConfiguration.getIncompatibleImprovements().- Since:
- 2.3.22
-
getObjectWrapper
Should be final; don't override it. OverridecreateObjectWrapper()instead. -
getTemplatePath
Deprecated.Not called by FreeMarker code, and there's no point to override this (unless to cause confusion).The value of theTemplatePathinit-param.nullif thetemplate_loadersetting was set in a customcreateConfiguration(). -
createRequestParametersHashModel
protected HttpRequestParametersHashModel createRequestParametersHashModel(jakarta.servlet.http.HttpServletRequest request) -
initializeServletContext
protected void initializeServletContext(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws jakarta.servlet.ServletException, IOExceptionCalled 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 requestresponse- the actual HTTP response- Throws:
jakarta.servlet.ServletExceptionIOException
-
initializeSession
protected void initializeSession(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response) throws jakarta.servlet.ServletException, IOExceptionCalled 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 requestresponse- the actual HTTP response- Throws:
jakarta.servlet.ServletExceptionIOException
-
preTemplateProcess
protected boolean preTemplateProcess(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Template template, TemplateModel model) throws jakarta.servlet.ServletException, IOExceptionCalled before the execution is passed toTemplate.process(Object, java.io.Writer). This is a generic hook you might use in subclasses to perform a specific action before the template is processed.- Parameters:
request- The HTTP request that we will response to.response- The HTTP response. The HTTP headers are already initialized here, such as theconteTypeand theresponseCharacterEncodingare already set, but you can do the final adjustments here. The responseWriterisn't created yet, so changing HTTP headers and buffering parameters works.template- The template that will get executedmodel- The data model that will be passed to the template. By default this will be anAllHttpScopesHashModel(which is aSimpleHashsubclass). Thus, you can add new variables to the data-model with theSimpleHash.put(String, Object)subclass) method. However, to adjust the data-model, overridingcreateModel(ObjectWrapper, ServletContext, HttpServletRequest, HttpServletResponse)is probably a more appropriate place.- Returns:
- true to process the template, false to suppress template processing.
- Throws:
jakarta.servlet.ServletExceptionIOException
-
postTemplateProcess
protected void postTemplateProcess(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Template template, TemplateModel data) throws jakarta.servlet.ServletException, IOExceptionCalled after the execution returns fromTemplate.process(Object, java.io.Writer). 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 requestresponse- the actual HTTP responsetemplate- the template that was executeddata- the data that was passed to the template- Throws:
jakarta.servlet.ServletExceptionIOException
-
getConfiguration
Returns theConfigurationobject used by this servlet. Please don't forget thatConfigurationis not thread-safe when you modify it. -
getDefaultOverrideResponseContentType
Returns the default value of the "OverrideResponseContentType" Servlet init-param. The method inherited fromFreemarkerServletreturns "always"; subclasses my override this.- Since:
- 2.3.24
-
Logger.