Java Template engine Freemarker

Source: Internet
Author: User

Concept
Freemarker is a template engine, a generic tool that generates text output based on a template, written in pure java.

It is a development package provided for the Java program Ape. It is not for the end user, but for the program ape to be able to embed the product they have developed the application.

Introduced
So. How is freemarker a tool? Freemarker is actually designed to generate HTML Web pages, especially by implementing a Java Servlet application based on the MVC pattern. The design concept of a dynamic page using the MVC pattern allows you to isolate the front-end designer from the program ape. All the people do their own work, play their best side.
Web designers can rewrite the display of the page without being affected by the code of the program ape, because the logic of the program and the design of the page have been separated. The page template code does not receive the effect of complex program code.

This separation of thought is also useful even for a program ape and page designer who are the same person, because separation makes the code simple and easy to maintain.
Although Freemarker also has some programming capabilities, it is common for the Java program to prepare the data to be displayed, generate the page by Freemarker, and display the prepared data (for example) through a template.

Freemarker is not a Web application framework. and is suitable as a component of the Web application framework. However, the Freemarker engine itself does not know the HTTP protocol or Java servlet exists. It only generates text content. Since this is the case, it is also well suited for non-web application development environments. The knowledge should be paid attention to. We use Freemarker as a component of the view layer to provide a ready-made solution to the MODEL2 application framework such as struts, and you can also use the JSP tag library in the template.



Characteristics

    • Common goals
Easy to embed into your product, lightweight, without the need for a servlet environment
Can generate a variety of text: HTML, XML, RTF, Java source code, and so on
Plug-in template loader. Ability to load templates from whatever source. such as local files, databases, etc.
You can generate the text as you want and save it to a local file. Send it as an email, send it back to the Web browser from the Web application
    • Powerful Template language
Create and change variables in a template
Named macros, capable of having positional parameters and nested content
Almost everywhere you can use complex expressions to specify values
All frequently used directives, include, if/elseif/else, loop structure
namespaces help you build and maintain reusable macro libraries, or divide a large project into modules without having to worry about name collisions
The output transform block, when the nested template fragment generates output. Convert HTML escape, compression, syntax highlighting, and so on. You can define your own conversions.
    • Common Data Model
Freemarker is not reflected directly to Java objects, Java objects are encapsulated by plug-in objects and are displayed in a template in a variable way
You can use abstract (interface) representations of objects (JavaBean, XML documents, SQL query result sets, and so on) to tell template developers how to use them. To keep it from being disturbed by technical details.
    • Preparing for the Web
Support for JSP tag libraries
Can be integrated into the MODEL2 Web application framework as a substitute for JSPs
Constructs built-in in the template language to handle typical web-related tasks such as HTML escaping
Design for MVC pattern, separate visual design and application logic, Detach page designer and program ape
    • Internationalization and localization of intelligence
Digital format Localization Sensitive
The same template in many different languages
Date and time format localization sensitive
Character Set intelligence (Unicode is used internally)
Non-US character sets can be used as identifiers (such as variable names)
    • Powerful XML processing power
Clear and intuitive access to the XML object model in the template
< #recurse > and < #visit > directives for recursive traversal of XML trees

Advantage
    • Ability to completely separate the presentation layer and business logic
The use of JSP development process, in the page a large number of business logic code, making the content of the page is very confusing, in the late large number of changes in the maintenance process becomes very difficult.


Freemarker does not support Java scripting code. The Freemarker principle is that the template + data model = output.

The template is only responsible for the performance of the data in the page. There is no logical code involved, and all logic is handled by the data model. The output that the user finally sees is created after the template and data model are merged.

    • can improve development efficiency
In the development of the past. The JSP pages are used to present the data. That is the so-called presentation layer.

We all know that. JSP in the first run when the need to convert to servlet class, the development phase of the function debugging, the need to frequently change the JSP, each change to compile and transform. So imagine how much time of the day we wasted on program compilation.
Relative to JSP. There is no compile-and-transform problem with freemarker template technology, so there is no such problem. And in the development process, we do not have to wait for the interface design developers to complete the page prototype, we then develop the program.


And, some specific systems. For example, in OA Workflow system, it is necessary to dynamically generate form technology, which provides a very good implementation basis.

The entire process is in progress. It's a lot easier to generate different forms.

    • Make the division of labor in the development process more clear
In the past, when using JSP to display data, some program apes are not familiar with interface design techniques. Otherwise the interface developer. Nor is it familiar with programming languages. For both, the alternating work itself is difficult. Sometimes the slightest careless. A program symbol may be deleted or removed from the entire page element. Make the page out of shape or program errors, so that the two parties to communicate with each other to solve the problem. Sometimes because of the time of the project, the amount of tasks and other factors, it may be a person to complete the work, which may increase the workload of a party developer.
Use Freemarker as the interface developer. Focus solely on creating HTML files, images, and other visualizations of Web pages, regardless of the data, while the program developer focuses on the system implementation. Responsible for preparing the data to be displayed for the page.



Insufficient

    • After you change the template, you may see data that has expired
Use Freemarker template technology to generate static HTML pages. Suppose once the template changes. Instead of updating the HTML page generated by the template in time. The user sees the data that is out of date.
    • The Freemarker variable must have a value
Freemarker template technology in the application process, the variables in the Freemarker must be assigned, assuming that no value is assigned, then an exception is thrown.

The Freemarker does not have a default null handle. It does not even accept a null value. If you want to avoid errors, you should apply the if/elseif/else instruction to the sentence, assuming that each variable is inferred, then add the trouble of programming instead.

    • The Freemarker map-qualified key must be a string. Other data types cannot be manipulated
The map problem, that is, a non-string key value cannot be supported in Freemarker. This will require some additional transformations in the case of some complex iterations. If you split a map into two or more maps.

    • Freemarker does not support cluster applications
In order to weave the convenience, the serialized things are put in the session, such as Session,request and so on. It is really handy in the development process, but assuming that the application is placed in the cluster, an error occurs.



A small demo
First of all. Need to download Freemarker jar package, here is a download link: Freemarker.jar
Then, put this freemarker.jar under the webroot\web-inf\lib folder of the WEB project
Finally, I posted my test class and shared it.
Freemarkertest Class Code

Import Java.io.bufferedwriter;import java.io.file;import Java.io.filewriter;import Java.io.ioexception;import Java.io.printwriter;import Java.util.hashmap;import Java.util.map;import Freemarker.template.configuration;import Freemarker.template.defaultobjectwrapper;import Freemarker.template.template;import Freemarker.template.templateexception;import Freemarker.template.templateexceptionhandler;import Junit.framework.testcase;public class Freemarkertest extends TestCase {private String dir = "e:/.../oa/testtotal/src/ Com/bjsxt/oa/freemarker ";p ublic void Testfreemarker () {Configuration CFG = new configuration (); try {// Where to load the template file cfg.setdirectoryfortemplateloading (new file);//define the location of the stencil, from the classpath, in relation to the path where the Freemarkermanager is loaded into the stencil// Cfg.settemplateloader (New Classtemplateloader (Freemarkermanager.class, "Templates"))// Sets the object wrapper Cfg.setobjectwrapper (new Defaultobjectwrapper ());//sets the exception handler Cfg.settemplateexceptionhandler ( Templateexceptionhandler.ignore_handler);//define data Model Map root = new HashMap (); Root.puT ("abc", "World.") Hello ");//through Freemarker to explain the template, you first need to obtain the Templates object template template = Cfg.gettemplate (" TEST.FTL ");// Defines the output after the template has been interpreted printwriter out = new PrintWriter (New BufferedWriter (dir+ "/out.txt")); try {// Explanation Template Template.process (root, out);} catch (Templateexception e) {e.printstacktrace ();}} catch (IOException e) {e.printstacktrace ();}}}


The following is a defined template TEST.FTL

Test.flt Code
First Test procedure: ${ABC}


The results of the last execution such as the following

output The OUT.txt file, the contents of the OUT.txt file such as the following:
The first Test procedure: the world. How are you doing



Java Template engine Freemarker

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.