Freemarker Instance Tutorial __freemarker

Source: Internet
Author: User

I. Introduction to Freemarker

Freemarker, a template engine, is a generic tool for generating static files based on templates, a development package for Java programmers, or a class library that is not intended for end users, but provides programmers with an application that can embed them in developing products.

Freemarker is written using pure Java, in order to improve the speed of page access, the need to put the page static, then Freemarker is used to generate HTML pages.

So far, Freemarker has been used more and more widely, not only for its powerful generation technology, but also for its ability to integrate well with spring.

Now start a layer to uncover its mystery.


Ii. conditions for preparation of Freemarker

Freemarker.2.3.16.jar Download Address: http://download.csdn.net/detail/ch656409110/4494067 (this jar bag is actually inside struts2)


three, Freemarker generation static page principle

Freemarker generate static pages, first need to use their own definition of the template page, this template page can be the most common HTML, can also be nested freemarker in the value expression, tags or custom tags, and so on, and then backstage read this template page, Parse the corresponding operation of the tag, and then pass the parameter substitution in the form of key-value pairs to replace the value expression in the template, and then generate a new HTML page based on the configured path to achieve the goal of static access.


Iv. tags provided by freemarker

Freemarker provides a lot of useful tags, freemarker tags are < #标签名称 > so named, ${value} represents the contents of the output variable name, as follows:

1, List: The tag is mainly for iterative server-side pass over the list collection, such as: [HTML] view plain copy print? < #list namelist as names> ${names} </#list >

< #list NameList as names> 
  ${names} 
</#list >

Name is a loop variable that is taken when the list loop is Freemarker, which is equivalent to the following when parsing the list label:

[Java] view plain copy print for (String names:namelist) {System.out.println (names); }  

			for (String names:namelist) {
				System.out.println (names);
			}
2, if: The label is mainly to do if the use of, for example:

[HTML] view plain copy print < #if (names== "Chen Jing Revenge") > His weapon is: 15 ~ </#if >

< #if (names== "Chen Jing Revenge") >
 his weapon is: 15 ~
</#if >
This is the conditional judgment tag, and note that the conditional equation must be enclosed in parentheses, which is equivalent to:

[Java] view plain copy print? If (Names.equals ("Chen Jing)") {System.out.println ("his weapon is: 15 ~ ~"); }  

			if (Names.equals ("Chen Jing enmity")) {
				System.out.println ("His weapon is: 15 ~ ~");
			}

3, include: This label is used for importing files.

[HTML] view plain copy print < #include "include.html"/>

< #include "include.html"/>

This import tag is very useful, especially for page reuse.

In addition, you can use ${} to get the value in a static file, which is as convenient as an El expression.

Here's an example (static.html):

[HTML] View Plain copy print? <! doctype html public  "-//w3c//dtd html 4.01 transitional//en"   "http:// Www.w3.org/TR/html4/loose.dtd ">  

<!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 

Actual code:

[Java] View Plain copy print? package com.chenghui.test;      import java.io.file;   import  java.io.fileoutputstream;   import java.io.ioexception;   import  java.io.outputstreamwriter;   import java.io.writer;   import java.util.ArrayList;    import java.util.hashmap;   import java.util.list;   import  java.util.map;      import freemarker.template.configuration;   import  freemarker.template.defaultobjectwrapper;   import freemarker.template.template;   import freemarker.template.templateexception;      public class createhtml  {       public static void main (String[] args)  {            try {                //Create a suitable configration object                 configuration configuration = new configuration ( );                Configuration.setdirectoryfortemplateloading (New file ("d:\\project\\webproject\\webcontent\\web-inf\\ Template ");                Configuration.setobjectwrapper (New defaultobjectwrapper ());                configuration.setdefaultencoding ("UTF-8");    // This must be set, otherwise in the generated page   will garbled                 Gets or creates a stencil.                template template  = configuration.gettemplate ("static.html");               Map<String,  Object> parammap = new hashmap<string, object> ();                parammap.put ("description", ) I'm learning to use Freemarker to generate static files. ");                               list<string> namelist =  new ArrayList<String> ();                namelist.add ("Chen Jing Revenge");                namelist.add ("Jade Son");                namelist.add ("nonfictional tuo");                Parammap.put ("NAMelist ",  namelist);                               map<string, object > weaponMap = new HashMap<String, Object> ();                weaponmap.put ("The,  Sword");                weaponmap.put ("Second",  "Kong Tong Yin");                weaponmap.put ("third",  "Nu wa Stone" ");               weaponmap.put (" fourth "),   "Shen Nong Ding");               weaponmap.put ("Fifth",  "Fuxi Qin");                Weaponmap.put ("Sixth ", " "Kunlun Mirror");                Weaponmap.put ("Seventh",  null);                parammap.put ("Weaponmap",  weaponmap);                                writer writer  = new outputstreamwriter (New fileoutputstream ("success.html ")," UTF-8 ");                Template.process (parammap, writer);                                System.out.println ("Congratulations, build Success ~ ~");           } catch  (ioexception e)  {              e.printstacktrace ();            } catch  (templateexception e)  {               e.printstacktrace ();            }                   }  }  

Package com.chenghui.test;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.OutputStreamWriter;
Import Java.io.Writer;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;

Import Java.util.Map;
Import freemarker.template.Configuration;
Import Freemarker.template.DefaultObjectWrapper;
Import Freemarker.template.Template;

Import freemarker.template.TemplateException; public class Createhtml {public static void main (string[] args) {try {///create an appropriate Configration object Configuration Co
			Nfiguration = new Configuration (); Configuration.setdirectoryfortemplateloading (New File ("D:\\project\\webproject\\webcontent\\web-inf\\template")
			);
			Configuration.setobjectwrapper (New Defaultobjectwrapper ());   Configuration.setdefaultencoding ("UTF-8");
			This must be set, otherwise the generated page will be garbled//get or create a template.
			Template Template = configuration.gettemplate ("static.html"); map<string, object> parammap = new hashmap<string, ObjeCt> (); Parammap.put ("description", "I'm learning to use Freemarker to generate static files.")
			
			");
			list<string> namelist = new arraylist<string> ();
			Namelist.add ("Chen Jing enmity");
			Namelist.add ("Jade Son");
			Namelist.add ("nonfictional extension");
			
			Parammap.put ("NameList", namelist);
			map<string, object> weaponmap = new hashmap<string, object> ();
			Weaponmap.put ("A", "Yuan Jian");
			Weaponmap.put ("Second", "Kong Tong Yin");
			Weaponmap.put ("Third", "Nu wa Stone");
			Weaponmap.put ("Fourth", "Shen Nong Ding");
			Weaponmap.put ("Fifth", "Fuxi Qin");
			Weaponmap.put ("Sixth", "Kunlun Mirror");
			Weaponmap.put ("seventh", null);
			
			Parammap.put ("Weaponmap", Weaponmap);
			Writer Writer = new OutputStreamWriter (New FileOutputStream ("success.html"), "UTF-8");
			
			Template.process (Parammap, writer);
		System.out.println ("Congratulations, build Success ~ ~");
		catch (IOException e) {e.printstacktrace ();
		catch (Templateexception e) {e.printstacktrace ();
 }
		
	}
}

Attached: Freemarker Tutorial

This kind of basically can calculate can be simple to do a little simple generation, but to use in practice, or poor very far, because Freemarker to the label is completely not meet our needs, this time we need to customize the label to complete our needs. Five, freemarker custom label

Freemarker Custom Label is to write their own tags, and then their own resolution, completely by themselves to control the input and output of the label, a great deal for programmers to provide a lot of space to play.

Based on steps:

The previous write tag needs to be added to the < after the #, but Freemarker to identify the custom tag needs to be followed by @, then you can define some parameters, when the program executes Template.process (Parammap, out); You will be able to parse all the Freemarker labels for the entire page.

Custom tags need to customize a class, and then implement Templatedirectivemodel, rewrite the Execute method, complete get parameters, according to the parameters do something, and so on.

Binding a custom label to a parsing class requires an instance of the parsing class to be placed in the Parammap, with the key stored in the same line as the custom label.

Note: In the custom label, if there is nothing in the label, the start tag and end tag can never be the same line, or it will error Freemarker.log.jdk14loggerfactory$jdk14logger error

I have been fooled, this is the freemarker existence of the bug.

The following is an example of static.html:

[HTML] view plain copy print? <! doctype html public  "-//w3c//dtd html 4.01 transitional//en"   "http:// Www.w3.org/TR/html4/loose.dtd ">  

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.