FreeMarker - FreeMarker and static pages introduction and use of

What is static pages

The dynamic page transformed into the static of html, reduce the number of interactions with the database to improve the access speed of the page. Is the server before the request has been fixed to the good stuff first compiled , and wait for a request to re- fill the dynamic data , do not wait for the request did not do anything too busy to death.

 

Why use a static web technology

Static web technology and caching techniques have in common is to reduce the pressure to access the database . The static pages are more suitable for large-scale and relatively less frequent data changes . Also static web page is also beneficial to SEO (search engine optimization). The pages show the pure static form, you can use this high-performance Nginx web server to deploy. Nginx can carry 50,000 concurrent, but only a few hundred Tomcat.

The use of third-party template engine to generate the corresponding html, common template engines: thymeleaf, freemarker, velocity.

 

What is FreeMarker

freemarker apache is an open source template engine, it is based on a template to generate text output . freemaker template engine can generate static page template and data.

 

FreeMarker advantage

1. advance to generate static pages based on templates and data when io stream pages are written to the hard disk, access direct access. Do not have access to the database, and can greatly improve the high concurrent read performance of the database, the database access was reduced ..

2. Because the page is generating good early, so the access speed, a good customer experience .

3. Since tomcat does not need to parse html browser can be accessed directly, so to reduce the high concurrent access tomcat pressure .

 

FreeMarker usage scenarios

1. Good news website news page generated in advance by freemarker

2. electricity supplier website page generation Product details well in advance through freemarker

The principle is: the page has a fixed pattern, and generates a read many times, the data changes as little as possible

 

FreeMarker running process

Schematics;

template:

1. The template is in the freemarker to .ftl for the extension of the file , in the template can use html tags, css, js, images and other static resources .

2. The template can be used to obtain data el expressions , but can not be used to judge and label jstl cycle, so the template engine will have its own set of tag libraries for our use.

data:

Data is typically stored in a relational database, or acquired or redis in mongodb.

 

Four elements in the template file

Part of the direct output: Text

NOTE: i.e., <# --...--> not output format

Interpolation (Interpolation): i.e., {..} $ section, the output data using a partial substitute model

FTL instructions: FreeMarker instruction, and HTML tags similar, plus # be distinguished former name, not output

 

FTL instruction

①assign instruction

The instructions for the page to define a variable that can be of a simple type may be an object type.

<#-- 定义一个myname变量 -->
<#assign myname = "柳成荫">
<#-- 定义一个myObj变量 -->
<#assign myObj = {"pet":"柯基","age":2}>
<h5>${myname}的宠物${myObj.pet}今天${myObj.age}岁啦!</h5>

②list instruction

Through the collection, _has_next for determining whether there is a next element, _index subscript indicates the index

<#list userList as user>
    下标:${user_index},姓名:${user.name},年龄:${user.age}<br>
    <#-- _has_next用于判断是否还有下一个元素 -->
    <#if user_has_next><em style="color: red">下一个数据是:</em></#if><br>
</#list>

③if instruction

<#if myname="柳成荫">
    <h5>myname是柳成荫</h5>
<#else>
    <h5>myname不是柳成荫</h5>
</#if>

④include instruction

<#include "header.ftl">

Built-in functions

Built-in function syntax:? Variable ++ function names

① get set size

<#-- 获取集合大小 -->
userList集合共有${userList?size}个元素<br>

② convert JSON string object

<#-- 转换JSON字符串为对象 -->
<#assign jsonStr="{'name':'九月清晨','age':'25'}" />
<#assign data=jsonStr?eval/>
姓名:${data.name},年龄:${data.age}<br>

③ Date Format

<#-- 日期格式化 -->
当前日期:${today?date}<br>
当前时间:${today?time}<br>
当前日期+时间:${today?datetime}<br>
日期格式化:${today?string("yyyy年MM月")}<br>

④ digital converter to a string

Digital direct display, there will be a comma is required? C conversion.

<#-- 数字转换成字符串,数字直接显示会出现逗号 -->
正常打印price:${price}<br>
去除逗号:${price?c}<br>

⑤ null handling operators

<#-- 空值处理运算符,判断是否为空值 -->
<#if price??>
    price变量存在
<#else>
    price变量不存在
</#if><br>

⑥ missing variable Default: "!"

<#-- 缺失变量默认值,可以判空,也可以对null做转换处理 -->
${price!'变量为空!'}<br>

Operators

① arithmetic operators

FreeMarker support comprises arithmetic operators: +, -, *, /,%

${1+5}<br>

② logical operators - Logical operators can only act on a boolean value, otherwise an error 

1, and logic: && 2, logic, or: ||. 3, logical negation:! 

③ comparison operators

Or = 1 ==: determining whether the two values ​​are equal

2 =:! Determine whether two values ​​are unequal. 

3> Or gt: determining the left to the right value is greater than the value 

4> or = gte: determining whether the value is greater than or equal to the right of the left value 

5 <Alternatively lt: judging value is smaller than the left to the right value 

6 <or = lte: determining whether the value is less than or equal to the right of the left value 

Note : = and = can be used! String, numeric and date to compare for equality, = and = both sides! Must be the same type of value , or an error.

 

Entry procedures - Appeal instructions, built-in functions such as presentations

① create Maven project (Jar Engineering)

② the introduction of pom-dependent

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

③ create a template file, create a folder under the resources ftl file, and create a MyFreemark.ftl file in the folder

④ create a class Peole

public class User {
    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

⑤ create a test class

public class TestFreemarker {
    public static void main(String[] args) throws Exception{
        // 1.创建配置
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 2.设置模板所在的目录 - 绝对位置
        configuration.setDirectoryForTemplateLoading(new File("F:\\Programming Study\\MavenProject\\freeMarkProject\\src\\main\\resources\\ftl"));
        // 3.设置字符集 - html页面的字符集
        configuration.setDefaultEncoding("utf-8");
        // 4.设置加载的模板
        Template template = configuration.getTemplate("MyFreemark.ftl");
        // 用户集合
        List userList = new ArrayList();
        userList.add(new User("用户1",18));
        userList.add(new User("用户2",20));
        userList.add(new User("用户3",22));
        // 5.设置数据
        Map map = new HashMap();
        map.put("name","柳成荫");
        map.put("message","欢迎登录!");
        map.put("userList",userList);
        map.put("today",new Date());
        map.put("price",199710);
        // 6.生成的文件叫什么名字,放在哪里
        Writer out = new FileWriter(new File("d:\\testFreemark.html"));
        // 7.输出
        template.process(map,out);
        // 8.关闭IO流
        out.close();
    }
}

⑥ effect

 

Published 63 original articles · won praise 13 · views 7634

Guess you like

Origin blog.csdn.net/qq_40885085/article/details/104111328
Recommended