Freemaker page static technology

Posted by PrivatePile on Wed, 09 Feb 2022 16:11:10 +0100

I background

When accessing dynamic pages, users need to send a request to query the database through ajax to obtain dynamic data for display, but if the page has a large amount of visits and the data in the database changes frequently
The rate is not high, which will cause great access pressure to the database. How to decompress the database and improve the system performance? The answer is static pages.

Page static is actually changing the original dynamic web page (for example, the web page that dynamically obtains the data in the database and displays it through ajax request) into a static web page generated by static technology. In this way, when users visit the web page, the server will directly respond to the static html page to users, without the process of dynamically querying the database.

II Page static technology freemaker

FreeMarker is a template engine written in Java language, which generates text output based on templates. FreeMarker and Web content
Device independent, that is, when the Web is running, it does not know Servlet or HTTP. It can not only be used as the implementation technology of presentation layer, but also
It can be used to generate XML, JSP or Java.

III Freemarker basic operation

1. Introduce dependency:

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

2. Create template file:

There are four elements in the template file:

  • html native text
  • Notes, i.e. < #--- >
  • Interpolation:: i.e. ${...} part, will replace the output with part in the data model
  • FTL instruction: FreeMarker instruction is similar to HTML tag. It is distinguished by adding # to the name and will not be output
    Freemaker template files usually have a suffix of ftl

Write template file:

<html> 
	<head>
		<meta charset="utf-8"> 
		<title>Freemarker introduction</title> 
	</head>
	<body>
<#--I'm just a comment. I won't have any output -- >
 ${name}Hello, ${message} 
 	</body>
</html>

Generate html file through java combined with template file

public static void main(String[] args) throws Exception{ 

//1. Create configuration class 

	Configuration configuration=new Configuration(Configuration.getVersion()); 

//2. Set the directory where the template is located 

	configuration.setDirectoryForTemplateLoading(new File("D:\\ftl")); 

//3. Set character set 

	configuration.setDefaultEncoding("utf-8"); 

//4. Load the template (the template file with ftl suffix in the template directory)

	Template template = configuration.getTemplate("test.ftl"); 

//5. Create data model 

	Map map=new HashMap(); 

	map.put("name", "Zhang San"); 

	map.put("message", "welcome!"); 

//6. Create the Writer object and create the directory generated by html

	Writer out =new FileWriter(new File("d:\\test.html")); 

//7. Output 

	template.process(map, out); 

//8. Close the Writer object 

	out.close(); 

}

The generated html files are as follows: (the corresponding ${name}, ${message} are successfully replaced)

<html> 
	<head>
		<meta charset="utf-8"> 
		<title>Freemarker introduction</title> 
	</head>
	<body>
 Hello, Zhang San. Welcome 
 	</body>
</html>

3.FTL instruction:

  • assign instruction: used to define a variable on the page
  1. Define a simple type

< #assign linkman = "Mr. Zhou" >
Contact: ${linkman}

  1. Define a json object

< #assign info = {"mobile": "123456", "address": "Earth"} >
Tel.: ${info.mobile} address: ${info.address}

  • include directive: used to nest template files. Introducing one template into another
<!--head.ftl-->
<h1> hello</h1>
<!--test.ftl-->
<#include "head.ftl"/>
<br>
world

Finally generated html file

<h1>hello</h1>
<br>
world
  • if instruction: use the instruction to judge in the template file
<#if success=true>
	 You have passed the real name certification 
<#else>
 	 You have not passed the real name certification 
</#if>

In java:

map.put("success", true);
  • List instruction: the list instruction is used to traverse

template file

<#list>
Trade name: ${goods.name} Price: ${goods.price}
<br>
</#list>

java code

List goodsList=new ArrayList(); 
Map goods1=new HashMap(); 
goods1.put("name", "Apple"); 
goods1.put("price", 5.8); 
Map goods2=new HashMap(); 
goods2.put("name", "Banana"); 
goods2.put("price", 2.5); 
Map goods3=new HashMap(); 
goods3.put("name", "a mandarin orange"); 
goods3.put("price", 3.2); 
goodsList.add(goods1); 
goodsList.add(goods2); 
goodsList.add(goods3); 
map.put("goodsList", goodsList);

The above is the basic usage of freemaker, but freemaker is much more complex in actual development.

IV Freemaker integrates spring

Dependency introduction is the same as above:

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

spring configuration file:

<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> 
<!--Specify the directory where the template file is located--> 
	<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
 <!--Specify character set-->
 	<property name="defaultEncoding" value="UTF-8" /> 
</bean> 
 <context:property-placeholder location="classpath:freemarker.properties"/>
//The location where the generated html file is stored
out_put_path=D:/ideaProjects/zj/health_mobile/src/main/webapp/pages

General generated html file style:

/**
* templateName Name of the template file
* htmlPageName The name of the generated html file
* map  Mapping relationship assigned to ${}
*/
 public void generteHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//Get configuration object
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //Construct output stream
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //output file
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

V Summary:

1. What is web page static technology

With the increase of user visits and data, web page static technology scheme is becoming more and more popular.
What is web page static technology? In short, it is to show the web page in a pure static way.

2. Comparison between web page static technology and cache technology

Common ground: both can reduce the access pressure of the database.

difference:

(1) Caching technology (such as redis) is suitable for small-scale data. And some frequently changing data.

(2) Web page static technology is suitable for large-scale but infrequently changing data.

3. Application scenario of web page static technology

(1) The article type channels of news portals generally use the static technology of web pages. Clicking on the news will directly jump to the static page.
(2) The product details page of e-commerce websites is also very commonly used. When we store products, we will generate a static page. Clicking on the product details will directly jump to the static page of the generated product details.
(3) Web page static technology can be combined with Nginx, a high-performance web server, to improve the amount of concurrent visits.

4. What is FreeMarker

FreeMarker is a template engine written in Java language. It can generate output text (such as HTML web pages, configuration files, source code, etc.) through templates and data to be changed as a means to realize web page static technology. FreeMarker is much more used than some other technologies. For applications that frequently use the database for query but have little content update in the system, FreeMarker can be used to static the web page, so as to avoid a large number of database access requests and improve the performance of the website.

Additional links:
Freemaker official website

Topics: Java Front-end server