Use of FreeMaker in Java

Keywords: Big Data FreeMarker Attribute Java Spring

1. What is freemarker?

FreeMarker is a template engine written in Java language, which generates text output based on templates. FreeMarker has nothing to do with Web containers, that is, when the Web runs, it does not know about Servlet s or HTTP. It can be used not only as a presentation layer implementation technology, but also to generate XML, JSP or Java.

At present, in enterprises, Freemarker is mainly used for static pages or page display.

2. The Use of Freemarker

Add freemarker's jar package to the project.

2.1 Maven Project Adding Dependency

<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.23</version>
</dependency>

2.2 wrong maven The project is joined accordingly jar Package to build path in

2.3 Principle:

3.Use steps:

Step 1: Create a Configuration Object, direct new An object. The parameters of the constructor are freemarker For the version number.
//Step 2: Set the path of the template file.
//Step 3: Set the character set used by the template file. Usually utf-8.
//Step 4: Load a template and create a template object.
//Step 5: Create a data set for template use, either pojo or map. It's usually Map.
//Step 6: Create a Writer object, generally create a FileWriter object, specify the name of the generated file.
//Step 7: Invoke the process method of the template object to output the file.
//Step 8: Close the flow.

3.1 Template:

Put on WEN-INF/ftl/hello.ftl In the document:
${hello}

3.2 Implementation code

    @org.junit.Test
    public void test() throws IOException, TemplateException {
        // Step 1: Create a Configuration object, directly new an object. The parameter of the constructor is the version number for freemarker.
        Configuration configuration = new Configuration(Configuration.getVersion());
        // Step 2: Set the path of the template file.
        configuration.setDirectoryForTemplateLoading(
                new File("D:\\Java\\Eclipse\\workspace_Test\\FreeMarker\\src\\main\\webapp\\WEB-INF\\ftl"));
        // Step 3: Set the character set used by the template file. Usually utf-8.
        configuration.setDefaultEncoding("utf-8");
        // Step 4: Load a template and create a template object.
        Template template = configuration.getTemplate("hello.ftl");
        // Step 5: Create a data set for template use, either pojo or map. It's usually Map.
        Map dataModel = new HashMap();
        // Adding data to the data set
        dataModel.put("hello", "this is my first freemarker test.");
        // Step 6: Create a Writer object, generally create a FileWriter object, specify the name of the generated file.
        Writer out = new FileWriter(new File("D:\\Java\\Eclipse\\workspace_Test\\FreeMarker\\out\\hello.html"));
        // Step 7: Invoke the process method of the template object to output the file.
        template.process(dataModel, out);
        // Step 8: Close the flow.
        out.close();
    }

4.Grammar of Templates

4.1 Visit map Medium key

${key}

4.2 Visit pojo Properties in

Student Object. School number, name, age
${key.property}

4.3 Fetch data from a collection

Recycling format:

<#list Data to be recycled as Cyclic data>
</#list>

Such as:

<#list studentList as student>
${student.id}/${studnet.name}
</#list>


4.4 Take the subscript in the loop

<#list studentList as student>
    ${student_index}
</#list>

4.5 judge

<#if student_index % 2 == 0>
<#else>
</#if>

4.6 Date type formatting

Direct value:${date}(date Is the attribute name.)If it comes from one Date Type data will report errors

${date?date} //2016-9-13
${date?time} //17:53:55
${date?datetime} //2016-9-13 17:53:55


4.7Null Processing of values

If you take a non-existent value directly(The value is null)Sometimes an exception will be reported.
${aaa}
//Handle: aaa!"Silentrecognizevalue"orpersonaaa!"Default value"or{aaa! }Represents empty strings

4.8 Include tag

<#include "Template name"> //(equivalent to inclusion in jstl)
  • 1

5.Freemarker Integration spring

5.1 Introduce jar package:

Freemarker's jar package
The jar package of Spring web mvc
Sping context support jar package

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>top.yubaojin</groupId>
    <artifactId>FreeMarker</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.13.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/</path>
                    <port>8080</port>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>



5.2 Create integration spring Configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <!-- Configuration Annotation Driver -->
    <mvc:annotation-driven />
    <!-- freemarker integration spring in -->
    <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>
    <!-- Configure package scanner, scan@Controller Annotated classes -->
    <context:component-scan base-package="top.yubaojin.controller" />
</beans>      


5.3web file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <display-name>FreeMarker</display-name>
    <!-- Front-end controller -->
    <servlet>
        <servlet-name>freemarker</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextConfigLocation Not required, if not configured contextConfigLocation, springmvc Configuration files default to: WEB-INF/servlet Of name+"-servlet.xml" -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>freemarker</servlet-name>
        <!-- Intercept all requests jsp Except -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>


5.4 Compiling test Controller

Requested url: /test
//Parameter: None
//Return value: ok (String, need to use @ResponseBody)
//Business logic:
1,from spring Obtained in containers FreeMarkerConfigurer Object.
2,from FreeMarkerConfigurer Object acquisition Configuration Object.
3,Use Configuration Object acquisition Template Object.
4,Create data sets
5,Creating the output file Writer Object.
6,Calling the template object process Method to generate files.
7,Close the flow.

package top.yubaojin.controller;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@Controller
public class FreeMarkerController {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @RequestMapping("/test")
    @ResponseBody
    public String test() throws IOException, TemplateException {
        // 1,from spring Obtained in containers FreeMarkerConfigurer Object.
        // 2,from FreeMarkerConfigurer Object acquisition Configuration Object.
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        // 3,Use Configuration Object acquisition Template Object.
        Template template = configuration
                .getTemplate("hello.ftl");
        // 4,Create data sets
        Map dataModel = new HashMap();
        dataModel.put("hello", "1000");
        // 5,Creating the output file Writer Object.
        //You need to create it manually under D:/Java/Eclipse/workspace_Test/FreeMarker/.outCatalog
        File file = new File("D:/Java/Eclipse/workspace_Test/FreeMarker/out/spring-freemarker.html");
    /*  if(!file.exists()) {
            file.createNewFile();
        }*/
        Writer out = new FileWriter(file);
        // 6,Calling the template object process Method to generate files.
        template.process(dataModel, out);
        // 7,Close the flow.
        out.close();
        return "OK";
    }
}



6.test

6.1 To configure Tomcat Plug-in operation maven build

6.2 Browser Request Test


//Result:

6.3 View results

Posted by BuzzStPoint on Tue, 29 Jan 2019 13:36:15 -0800