What is theFreeMarker?

FreeMarker is a template engine: a general-purpose tool that generates output text (HTML pages, profiles, emails, source code) based on templates and data sources. It is a Java class library originally designed to generate HTML pages in an MVC-style Web development framework, and it is not tied to servlets or HTML or anything Web related. It can also be used in non-Web application environments.

Templates are written using FreeMarker Template Language(FTL). EL expressions that work like JSPS. In a template you can focus on how to present the data, and outside of the template you can focus on what data to present.

Why useFreeMarker?

  1. FreeMarker renders based on data models and templates, separating the business logic from the presentation layer. In JSP development, pages have a lot of business logic that can be difficult to maintain and read, and using FreeMarker avoids this problem.

  2. ** * is conducive to division of labor and cooperation. **HTML designers can focus on the design of the page without facing the business logic of the page, and modify the page code without requiring programmers to write and reinterpret the code.

  3. ** Improve development efficiency. ** Compared to JSP, FreeMarker does not need to be recompiled after every change, so it can be a significant time saver in development debugging.

  4. ** helps improve access speed. ** Static pages generated by FreeMarker are recommended for pages that do not change frequently. Rather than JSP pages that are dynamically generated every time.

  5. ** can increase concurrency. ** For example, a single Tomcat container can support only a few hundred concurrent requests. If static pages are placed on a better nginx server, they can support tens of thousands of concurrent requests.

  6. Static pages are more SEO friendly.

  7. ** does not take up PermGen space for the JVM. ** Because it is not compiled into classes, it does not take up space in the Eternal generation of the Web server, avoiding OutOfMemoryError: PermGen Space.

How to useFreeMarker?

Used in Java

	@Test
	public void testFreeMarker(a) throws Exception {
		// Add freemarker's JAR package to the project
		// Create a Configuration object
		Configuration configuration = new Configuration(Configuration.getVersion());
		// Tells config where the object template file is stored.
		configuration.setDirectoryForTemplateLoading(new File("ftl directory absolute path"));
		// Set the default character set for config. The general is utf-8
		configuration.setDefaultEncoding("utf-8");
		// Get template object from config object. You need to name a template file.
		Template template = configuration.getTemplate("test.ftl");
		// Create the data set required by the template. This can be a Map object or a POJO that puts all the data needed by the template into the dataset.
		Map root = new HashMap<>();
		root.put("hello"."hello freemarker");
		// Create a Writer object and specify the path and name of the generated file.
		Writer out = new FileWriter(new File("out html file absolute path"));
		// Call the process method of the template object to generate a static file. You need two parameter datasets and a Writer object.
		template.process(root, out);
		// Close the Writer object.
		out.flush();
		out.close();
	}
Copy the code

Template loader

It is also possible to use a template loader without specifying an absolute path. FreeMarker provides a template loader that loads templates directly from the data source.

  • ClassTemplateLoader: Loads templates from the classpath.

  • FileTemplateLoader: Loads templates from a specified folder in the file system.

  • StringTemplateLoader: Loads templates from a string Map.

  • URLTemplateLoader: Loads templates from a URL. You must implement the getURL method.

  • WebappTemplateLoader: Loads templates from the servlet context.

Usage:

Configuration configuration = new Configuration();
configuration.setTemplateLoader(
new WebappTemplateLoader(servletContext, "WEB-INF/content"));
Copy the code

For use in projects

For use in projects, it can be hosted directly to the framework.

Add the dependent

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> < version > 4.1.3. RELEASE < / version > < / dependency > < the dependency > < groupId > org. Freemarker < / groupId > < artifactId > freemarker < / artifactId > < version > 2.3.23 < / version > < / dependency >Copy the code

Configure the spring

<bean id="freemarkerConfig"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
		<property name="defaultEncoding" value="UTF-8" />
	</bean>
Copy the code

Then use it to get the Configuration object from FreeMarkerConfigurer:

Configuration configuration = freeMarkerConfigurer.getConfiguration();
Copy the code

FreeMarker basic syntax

A simple type

Use something like an EL expression.

${hello}
Copy the code

Packing type

<html>
<head>
	<title>${title}</title> </head> <body> <label>${student.id}<br> <label> Name: </label>${student.name}<br>
</body>
</html>
Copy the code

Iterate over collections/arrays

<#list people as p>
	${p.id}/${p.name}
</#list>
Copy the code

Gets the current iteration index

<#list people as p
	${p_index}
</#list>
Copy the code

Add a judgment condition

<# the if condition >
<#else>
</#if>
Copy the code

The date type

# default format1: the date${cur_time? date}2: datetime${cur_time? datetime}3: time${cur_time? time}

# Custom format
${cur_time? string("yyyy-MM-dd HH:mm:ss")}
Copy the code

Handle null values

map.put(“val”,null)

Val value is:${val! }
Copy the code

When val is null, an empty string is displayed, that is

Val value is:Copy the code

You can also specify the default value if the value is null.

${val!" The default value "}
Copy the code

You can also use conditional statements to make non-null judgments.

<#if curdate ?? >Current date:${curdate? string("yyyy/MM/dd HH:mm:ss")}
	<#else>The curdate attribute is null </#if>
Copy the code

include

Additional template fragments can be introduced.

<#include "/include/head.ftl">
Copy the code

Json support

? Eval can turn a string into a JSON object, which is then used as a wrapper type in a template.

<#assign user = userString? eval>
User:${user.name}
Copy the code

Shared variables

Data that is automatically added to all templates can be set up so that it can be used in all templates.

configuration.setSharedVariable("share_value_key"."share_value");
Copy the code

supplement

  • Pages that need to use FreeMarker are updated when the database is updated, otherwise users will end up with outdated pages.

  • The map key of the FreeMarker data model can only be String.