Freemarker template engine technology

(1) concept

FreeMarker is a template engine: a generic tool for generating output text (HTML web pages, emails, profiles, source code, etc.) based on templates and data to change. It is not intended for the end user, but is a Java class library, a component that programmers can embed in the product they are developing. FreeMarker is free and released under the Apache license version 2.0. The Template is written as FreeMarker Template Language (FTL), which is a simple, dedicated Language. You need to prepare data for display in a real programming language, such as database queries and business operations, and then the template displays the prepared data. In the template, you focus on how to present the data, and outside the template, you focus on what data to present.

② Working principle

All template view technologies work similarly, which means FreeMarker and JSP are pretty much the same. Template files and data models are necessary components of template view technology to generate HTML pages.

Data model (Java) + template file (.ftl.jsp file) = output (HTML,XML, source file)Copy the code

JSP makes up for the deficiency of HTML page generated by Servlet in Web system, but it can only be applied to Web system to generate HTML page. FreeMarker works not only on Web systems, but also on Java systems, generating Java, XML, etc., so it’s much more versatile. When used, you need to add dependencies to the project pom.xml file.

< the dependency > < groupId > org. Freemarker < / groupId > < artifactId > freemarker < / artifactId > < version > 2.3.19 < / version > </dependency>Copy the code

When used in SpringMVC, you need to include the corresponding view parser

<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <! -- <property name="templateLoaderPath" value="/WEB-INF/ftl/" /> --> <property name="templateLoaderPaths"> <list> <value>/WEB-INF/ftl/</value> <value>classpath:/ftl/</value> </list> </property> <property name="freemarkerSettings"> <props> <prop key="defaultEncoding">UTF-8</prop> <! By default, FreeMarker checks every 5 seconds to see if the template has been updated and reloads and analyzes the template if it has. But checking regularly to see if templates are updated can be time-consuming. If your application is running in production mode and you don't expect templates to be updated very often, you can extend the update delay to an hour or more. You can do this by setting the freemarkerSettings property to template_update_delay, where 0 means reloading each time --> <prop key="template_update_delay">0</prop> <prop key="default_encoding">UTF-8</prop> <prop key="number_format">0.##########</prop> <prop key="datetime_format">yyyy-MM-dd  HH:mm:ss</prop> <prop key="classic_compatible">true</prop> <prop key="template_exception_handler">ignore</prop> </props> </property> </bean> <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver" p:prefix="/" p:suffix=".ftl"> <property name="cache" value="false" /> <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" /> <property name="contentType" value="text/html; charset=UTF-8"></property> <property name="exposeRequestAttributes" value="true" /> <property name="exposeSessionAttributes" value="true" /> <property name="exposeSpringMacroHelpers" value="true" /> <property name="requestContextAttribute" value="base"></property> <property name="order" value="0"></property> </bean>Copy the code

③ Basic grammar

The ${… }

FreeMarker will print the real value to replace the expression in curly braces, which is called Interpolation.

< p style = "max-width: 100%; clear: both;Copy the code

Comments are similar to HTML comments, but they are identified with <#– and –>. Unlike HTML comments, FTL comments do not appear in the output (not on the visitor’s page) because FreeMarker skips them.

<#if condition>
    ...
<#elseif condition2>
    ...
<#elseif condition3>
    ...
<#else>
    ...
</#if>
Copy the code

FTL tags have some similarities to HTML tags, but they are FreeMarker directives and are not printed in the output. The names of these tags begin with #. (User-defined FTL tags use @ instead of #)

(4) example

Bean. FTL file

package ${packageName}.bean;
public class ${className} {
}
Copy the code

Java code

// Create a Freemarker Configuration object Configuration CFG = new Configuration(); / / set the default location (path) CFG. SetDirectoryForTemplateLoading (new File (" ")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); // paramMap = new HashMap(); String className = "User"; paramMap.put("packageName", "com.atguigu.crowdfunding"); paramMap.put("className", className); Template t = cfg.getTemplate("bean.ftl"); // WriterOut = new OutputStreamWriter(new FileOutputStream(new File(" user.java ")), "utF-8 "); // Execute t.croess (paramMap, out);Copy the code

⑤ Common grammar

[1]

<#if condition>
    ...
<#elseif condition2>
    ...
<#elseif condition3>
    ...
<#else>
    ...
</#if>
Copy the code

[2]

<#list users as user>
    ${user.name},${user_index}
</#list>
Copy the code

[3]

<#include "xxxx.ftl"> 
Copy the code

[4] expression

expression instructions
${Request.member.name} Read data from the Request field
${Session.member.name} Read data from the Session field
${Application.member.name} Read data from the Application domain
${RequestParameters[‘id’]} Read request parameters
${book.name?if_exists } Used to determine if it exists, and output the value
The ${book. The name? The default (‘ XXX ‘)} The default value of XXX
${book.name!” xxx”} The default value of XXX
${book.date? string(‘yyyy-MM-dd’)} The date format
s? html The string is HTML encoded
s? cap_first Capitalize the first letter of the string
s? lower_case Converts a string to lowercase
s? trim Remove whitespace before and after the string
s? size Gets the number of elements in the sequence

SpringBoot uses FreeMarker

(1) rely on

    		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>
Copy the code

② Add related configurations

spring.freemarker.allow-request-override=false
spring.freemarker.allow-session-override=false
spring.freemarker.cache=true
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.enabled=true  
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=true
spring.freemarker.prefer-file-system-access=false
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.settings.template_update_delay=0
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.classic_compatible=true 
spring.freemarker.order=1
Copy the code

One of the most important is the spring. A freemarker. Suffix and spring.. Freemarker template – loader – path, other configuration items can use the default values.

@RequestMapping("/testftl") public String testFtl(Model model) { model.addAttribute("message", "good news!!!" ); return "target"; }Copy the code

 

Freemarker integrates simple applications from Maven

Freemarker has been used in distributed projects before

 

 

The project is on my Github

It can also be downloaded on Baidu Cloud

Note: After importing projects, you need to modify them accordingly. Here I share my Maven repository to prevent all imported projects from being red.