当前位置:网站首页>[template engine] microservice Learning Notes 6: freemaker
[template engine] microservice Learning Notes 6: freemaker
2022-07-25 03:16:00 【Driver Zhao Si】
Personal profile :
> Personal home page : Driver Zhao Si
> Direction of study :JAVA The backend development
> The best time to plant a tree is ten years ago , The second is now !
> The articles :SpringBoot Project integration wechat payment
> 🧡 If you like it, please pay a little attention , Your support is my biggest motivation .
Preface :
1. Based on Springboot The single project introduction of has been completed , As for the realization of other functions in the project, I'm not going to introduce them here , Because the knowledge involved is not difficult , And they are all simple CRUD operation , If you are interested, you can send me a private message. I'll see if I want to write a few articles to introduce .
2. Complete the previous stage of learning , I put myself into the study of microservices , The tutorials used are B The microservice tutorial of dark horse on the website . Because my memory is not very good , So for the study of new things, I prefer to take notes to enhance understanding , Here I will summarize the key contents of my notes and post them to “ Micro service learning ” In the notes column . I'm Zhao Si , A programmer with pursuit , I hope you can support me a lot , It would be better if you could give me some attention .
Catalog
One :🧸freemarker brief introduction
1.🧩 Create a project & Introduce dependencies
3、 ... and :🧸 Template testing
1.🧩 Create an entity class to test
Four :🧸Freemarker Common grammar
2:🧩 Set instruction (Map and List)
2.1: Create the corresponding controller
5.1: Determine whether a variable is used “??”
5.2: The default value of the missing variable is “!”
6.1: And the size of a collection
6.4: take json String to object
7.1: modify application.yml file
7.2: stay test Create a test class
One :🧸freemarker brief introduction
FreeMarker Is a template engine : It's based on the template and the data to be changed , And used to generate output text (HTML Webpage , E-mail , The configuration file , Source code, etc ) General tools for . It's not for end users , It is a Java Class library , It's a component that programmers can embed in their products .
The template is written as FreeMarker Template Language (FTL). It's simple , Special language , It's not like PHP That mature programming language . That means preparing data for display in real programming languages , For example, database query and business operation , After that, the template shows the prepared data . In the template , You can focus on how to present data , Outside of the template, you can focus on what data to show .
frequently-used java The template has jsp、Velocity、thmeleaf、freemarker etc. , The difference between them is as follows :
1.Jsp by Servlet special , Cannot be used alone .
2.Thymeleaf For new technology , More powerful , But the efficiency of implementation is relatively low .
3.Velocity from 2010 Updated in 2.0 After version , There is no update .Spring Boot The official in the 1.4 This is no longer supported after version , although Velocity stay 2017 The year version is iterated , But it's too late .
4.Freemarker Good performance , Is a powerful and lightweight template language .
Two :🧸 Environment building
1.🧩 Create a project & Introduce dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- apache Yes java io Package tool library -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>2.🧩 Add configuration file
server:
port: 8881 # Service port
spring:
application:
name: freemarker-demo # Specify the service name
freemarker:
cache: false # Turn off template caching , Convenient test
settings:
template_update_delay: 0 # Check the template update delay time , Set to 0 Means to check immediately , If the time is longer than 0 There will be caches that are not convenient for template testing
suffix: .ftl # Appoint Freemarker The suffix of the template file 3、 ... and :🧸 Template testing
1.🧩 Create an entity class to test
package com.my.freemarker.entity;
import lombok.Data;
import java.util.Date;
@Data
public class Student {
private String name;
private int age;
private Date birthday;
private Float money;
}
2.🧩 Create a template
stay resources Create templates, This directory is freemarker The default template storage directory .
stay templates Create a template file under 01-basic.ftl , The interpolation expression in the template will eventually be freemarker Replace with specific data .
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World!</title>
</head>
<body>
<b> Plain text String Exhibition :</b><br><br>
Hello ${name} <br>
<hr>
<b> object Student Data presentation in :</b><br/>
full name :${stu.name}<br/>
Age :${stu.age}
<hr>
</body>
</html>3.🧩 establish Controller
package com.my.freemarker.controller;
import com.my.freemarker.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class helloController {
@GetMapping("/basic")
public String helloTest(Model model){
//1. Plain text formal parameters
model.addAttribute("name","freemarker");
//2. Entity class related parameters
Student stu = new Student();
stu.setName(" Xiao Ming ");
stu.setAge(19);
stu.setMoney(100F);
model.addAttribute("stu",stu);
return "01-basic";
}
}
4.🧩 Create startup class
package com.my.freemarker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FreemarkerApplication {
public static void main(String[] args) {
SpringApplication.run(FreemarkerApplication.class,args);
}
}
5.🧩 To test
Browser input http:localhost:8881/basic

You can see that the data is successfully displayed .
Four :🧸Freemarker Common grammar
1:🧩 Basic grammar types
1. notes , namely <#-- Content -->, The content between them will be freemarker Treat as comments
2. interpolation (interpolation): namely ${..} part ,freeremarker Will replace... With real values ${..}
3.FTL Instructions : and HTML The mark is similar to , Add... Before your name # To distinguish ,Freeremarker Will parse expressions or logic in tags
<# > FTL Instructions </#>4. Text , Enter text information , These are not freeremarker Notes 、 interpolation 、FTL The content of the instruction will be freeremarker Ignore parsing , Output its contents directly .
2:🧩 Set instruction (Map and List)
2.1: Create the corresponding controller
@GetMapping("/list")
public String list(Model model){
//------------------------------------
Student stu1 = new Student();
stu1.setName(" cockroach ");
stu1.setAge(18);
stu1.setMoney(1000.86f);
stu1.setBirthday(new Date());
// Little red object model data
Student stu2 = new Student();
stu2.setName(" Xiaohong ");
stu2.setMoney(200.1f);
stu2.setAge(19);
// Store the data of two object models in List Collection
List<Student> stus = new ArrayList<>();
stus.add(stu1);
stus.add(stu2);
// towards model In the store List Aggregate data
model.addAttribute("stus",stus);
//------------------------------------
// establish Map data
HashMap<String,Student> stuMap = new HashMap<>();
stuMap.put("stu1",stu1);
stuMap.put("stu2",stu2);
// 3.1 towards model In the store Map data
model.addAttribute("stuMap", stuMap);
return "02-list";
}2.2: Template implementation
stay templates Add... To the package "02-list.ftl"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World!</title>
</head>
<body>
<#-- list Data display -->
<b> Exhibition list Medium stu data :</b>
<br>
<br>
<table>
<tr>
<td> Serial number </td>
<td> full name </td>
<td> Age </td>
<td> wallet </td>
</tr>
<#list stus as stu>
<tr>
<td>${stu_index+1}</td> <!-- index: Get the subscript of the loop , The method of use is in stu Add after "_index", Its value is from 0 Start -->
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.money}</td>
</tr>
</#list>
</table>
<hr>
<#-- Map Data display -->
<b>map Data display :</b>
<br/><br/>
<a href="###"> Mode one : adopt map['keyname'].property</a><br/>
Output stu1 Student information :<br/>
full name :${stuMap['stu1'].name}<br/>
Age :${stuMap['stu1'].age}<br/>
<br/>
<a href="###"> Mode two : adopt map.keyname.property</a><br/>
Output stu2 Student information :<br/>
full name :${stuMap.stu2.name}<br/>
Age :${stuMap.stu2.age}<br/>
<br/>
<a href="###"> Traverse map Two student information :</a><br/>
<table>
<tr>
<td> Serial number </td>
<td> full name </td>
<td> Age </td>
<td> wallet </td>
</tr>
<#list stuMap?keys as key >
<tr>
<td>${key_index}</td>
<td>${stuMap[key].name}</td>
<td>${stuMap[key].age}</td>
<td>${stuMap[key].money}</td>
</tr>
</#list>
</table>
<hr>
</body>
</html>2.3: test
Type in the browser address bar http:localhost:8881/list

You can see that the data is successfully displayed
3.🧩if Instructions
if An instruction is a judgment instruction , It is commonly used. FTL Instructions ,freemarker Encountered while parsing if They make judgments , If the condition is true, output if In the middle , Otherwise, skip the content and no longer output .
<#if ></if>Use list The data in the instruction is used as the data model , Name it “ Xiaohong ” The data output of is red
<#list stus as stu>
<#if stu.name = ' Xiaohong '>
<tr style="color: red">
<td>${stu_index+1}</td> <!-- index: Get the subscript of the loop , The method of use is in stu Add after "_index", Its value is from 0 Start -->
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.money}</td>
</tr>
<#else >
<tr>
<td>${stu_index+1}</td>
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.money}</td>
</tr>
</#if>
</#list>
You can see that success “ Xiaohong ” Turn red .
4.🧩 Operator
4.1: Arithmetic operator
FreeMarker Expression supports +、-、*、/、% operation , Just put the operation expression into ${} Then you can .
4.2: Comparison operator
=perhaps==: Determine if two values are equal .!=: Judge whether the two values are not equal .>perhapsgt: Judge whether the left value is greater than the right value>=perhapsgte: Judge whether the left value is greater than or equal to the right value<perhapslt: Determine whether the left value is less than the right value<=perhapslte: Judge whether the left value is less than or equal to the right value
4.3: Logical operators
Logic and :&&
Logic or :||
Logic is not :!
Logical operators can only work on Boolean values , Otherwise there will be a mistake .
5.🧩 Null processing
5.1: Determine whether a variable is used “??”
Usage for :variable??, If the variable exists , return true, Otherwise return to false
example : To prevent stus If it is empty, you can add the following judgment :
<#if stus??>
<#list stus as stu>
......
</#list>
</#if>5.2: The default value of the missing variable is “!”
Use ! To specify a default value , Display the default value when the variable is empty
example : ${name!''} Said if name Displays an empty string if it is empty .
If it is a nested object, it is recommended to use () Cover up
example : ${(stu.bestFriend.name)!''} Express , If stu or bestFriend or name If it is empty, the empty string will be displayed by default .
6.🧩 Built-in functions
Built in function syntax format : Variable +?+ The name of the function
6.1: And the size of a collection
${ Collection name ?size}
6.2: Date formatting
Show the year, month and day : ${today?date} Display minutes and seconds :${today?time} Show date + Time :${today?datetime} Custom formatting : ${today?string("yyyy year MM month ")}
6.3: Built-in functions c
model.addAttribute("point", 102920122);
point It's digital , Use ${point} The value of this number will be displayed , Use commas to separate every three digits .
If you don't want to display numbers separated by every three digits , have access to c Function converts a numeric type to a string and outputs
${point?c}
6.4: take json String to object
An example :
Which USES assign label ,assign The function of is to define a variable .
<#assign text="{'bank':' Industrial and Commercial Bank of China ','account':'10101920201920212'}" />
<#assign data=text?eval />
Opening bank :${data.bank} account number :${data.account}7.🧩 Static testing
Previous tests have been SpringMVC take Freemarker As a view parser (ViewReporter) To integrate into the project , In the work , Sometimes you need to use Freemarker Native Api To generate static content , Now let's learn about native Api Generate text file ( Select generate here html file ).
7.1: modify application.yml file
Add the configuration information of the following template storage location , The full configuration is as follows :
server:
port: 8881 # Service port
spring:
application:
name: freemarker-demo # Specify the service name
freemarker:
cache: false # Turn off template caching , Convenient test
settings:
template_update_delay: 0 # Check the template update delay time , Set to 0 Means to check immediately , If the time is longer than 0 There will be caches that are not convenient for template testing
suffix: .ftl # Appoint Freemarker The suffix of the template file
template-loader-path: classpath:/templates # Template storage location 7.2: stay test Create a test class
package com.my.freemarker.test;
import com.my.freemarker.FreemarkerApplication;
import com.my.freemarker.entity.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
@SpringBootTest(classes = FreemarkerApplication.class)
@RunWith(SpringRunner.class)
public class FreemarkerTest {
@Autowired
private Configuration configuration;
@Test
public void test() throws IOException, TemplateException {
//freemarker Template object , Access to the template
Template template = configuration.getTemplate("02-list.ftl");
Map params = getData();
template.process(params,new FileWriter("d:/headlinesPro/list.html"));
}
private Map getData() {
Map<String,Object> map = new HashMap<>();
// Data model construction
Student stu1 = new Student();
stu1.setName(" cockroach ");
stu1.setAge(19);
stu1.setMoney(100F);
stu1.setBirthday(new Date());
Student stu2 = new Student();
stu2.setName(" Xiaohong ");
stu2.setAge(20);
stu2.setMoney(1000F);
stu2.setBirthday(new Date());
// Put two objects into List
List<Student> list = new ArrayList<>();
list.add(stu1);
list.add(stu2);
// towards map In the store list data
map.put("stus",list);
// establish mao data
HashMap<String,Student> stuMap = new HashMap<>();
stuMap.put("stu1",stu1);
stuMap.put("stu2",stu2);
// towards Map In the store Map data
map.put("stuMap",stuMap);
return map;
}
}
7.3: Result display

You can see the successful generation html file , Open file :

边栏推荐
- Bgy development small example
- Clothing ERP | ten advantages of clothing ERP for enterprises
- Idea configuration
- Threat report in June: new bank malware malibot poses a threat to mobile banking users
- JS foundation -- JSON
- Operator explanation - C language
- JS method encapsulation summary
- Learning Record V
- File permission management
- B. Almost Ternary Matrix
猜你喜欢
![[stm32f103rct6] motor PWM drive module idea and code](/img/a5/3010acff73c8913e967ff3a024877e.png)
[stm32f103rct6] motor PWM drive module idea and code

Reasons for not sending requests after uni app packaging

B. Making Towers

How chemical enterprises choose digital service providers with dual prevention mechanism

Banana pie bpi-m5 toss record (3) -- compile BSP

Unified return data format

mysql_ Master slave synchronization_ Show slave status details

Review all frames before sum of SSM frames

Publish the project online and don't want to open a port

mysql_ Record the executed SQL
随机推荐
Selenium framework operation steelth.min.js file hides browser fingerprint features
ECMAScript new features
mysql_ Case insensitive
Print the common part of two ordered linked lists
Test question f: statistical submatrix
JS construction linked list
Use and introduction of vim file editor
Solve the error: could not find 'xxxtest‘
JS common interview questions
Common methods of array
Operator explanation - C language
How to use two queues to simulate the implementation of a stack
ES6 - study notes
Color space (1) - RGB
How chemical enterprises choose digital service providers with dual prevention mechanism
Learning Record V
JS written test question -- promise, setTimeout, task queue comprehensive question
JS written test question -- prototype, new, this comprehensive question
JS written test -- regular expression
How is the virtual DOM different from the actual DOM?