Free Basic Concepts

Source: Internet
Author: User

I. Overview

Freemarker is a template engine, a generic tool that generates text output based on a template, written in plain Java, and Freemarker is designed to generate HTML Web pages, especially applications based on MVC patterns, although Freemarker has some programming capabilities , but usually the Java program prepares the data to be displayed, generates the page by Freemarker, and displays the prepared data through the template (e.g.)

Freemarker is not a Web application framework, but a component for the Web application framework. Freemarker is not container-independent because it does not know that HTTP or servlet;freemarker can also be applied to a non-web application environment, and Freemarker is better suited as a view component of a MODEL2 framework (such as Struts). You can also use the JSP tag library in the template. In addition, Freemarker is free of charge.

Ii. conditions of preparation for Freemarker

Freemarker.2.3.16.jar, this place is not posted. (This jar is actually inside struts2)


Third, freemarker the principle of generating static pages

Freemarker generate static page, first need to use the template page of their own definition, this template page can be the most common HTML, can also be nested freemarker in the value expression, label or custom label, etc., and then read the template page in the background, Parse the label to complete the corresponding operation, and then use the key-value pair to pass the parameter substitution template in the value expression, after the completion of the configured path to generate a new HTML page, to achieve the purpose of static access.

Four, Freemarker provides the label, currently only need to know these several

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

1, List: The label is mainly to iterate over the server side of the list of the collection, such as:

<namelist as names>  </#list>

Name is a loop variable that is taken at the time of the list loop, and Freemarker is equivalent to when parsing the list tag:

 for (String names:namelist) {   

2, if: The label is mainly to do if the use of judgment, such as:

<(names= = "Chen Revenge")>  </#if >

This is the conditional judgment tag, note that the conditional equation must be enclosed in parentheses , equivalent to:

if (Names.equals ("Chen Revenge")) {   System.out.println ("His weapon is: 15 ~ ~")


3. Include: This tag is used for importing files

<"include.html"/>

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

In addition, in the static file can use ${} to get the value, the value of the same way as the El expression, very convenient.

Here's an example (static.html):

<!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "> <HTML> <Head> <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"> <title>Insert Title here</title> </Head> <Body>Description: ${description}<BR/>collection size: ${namelist?size}<BR/>Iterate the list collection:<BR/> <#listNameList as names>This is the first ${names_index+1} person, called:<labelstyle= "Color:red">${names}</label>If judgment:<BR/> <#if(Names= = "Chen Revenge")>his weapon is: 15 ~ ~<#elseif(Names= = "Yu text extension")>    <#--Note that there is no return but the last->His weapon is: the Shaft sword ~<#else>Her trick is: Poison ~ ~</#if> <BR/> </#list>Iteration Map Collection:<BR/> <#listWeaponmap?keys as key>Key--->${key}<BR/>Value----->${weaponmap[key]! (" Null ")}<#--  Fremarker does not support NULL, can be used! Instead of an empty value. In fact, you can also give a default value of value-----${weaponmap[key]?default ("null")} can also be determined before the output is null < #if Weaponmap[key]??></#if>you can .<BR/> </#list>include import file:<BR/> <#include"Include.html"/>   </Body> </HTML> 

Actual code:

 Packagecom.chenghui.test; ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.OutputStreamWriter;ImportJava.io.Writer;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map; Importfreemarker.template.Configuration;ImportFreemarker.template.DefaultObjectWrapper;Importfreemarker.template.Template;Importfreemarker.template.TemplateException;  Public classcreatehtml { Public Static voidMain (string[] args) {Try {       //create an appropriate Configration objectConfiguration Configuration =NewConfiguration (); Configuration.setdirectoryfortemplateloading (NewFile ("D:\\project\\webproject\\webcontent\\web-inf\\template")); Configuration.setobjectwrapper (NewDefaultobjectwrapper ()); Configuration.setdefaultencoding ("UTF-8");//This must be set, or it will be garbled in the generated page//Gets or creates a template. Template template = Configuration.gettemplate ("static.html"); Map<string, object> parammap =NewHashmap<string, object>(); Parammap.put ("description", "I'm learning to use Freemarker to generate static files!" "); List<String> NameList =NewArraylist<string>(); Namelist.add ("Chen Revenge"); Namelist.add ("Jade Son"); Namelist.add ("Yu text extension"); Parammap.put ("NameList", NameList); Map<string, object> weaponmap =NewHashmap<string, object>(); Weaponmap.put ("First", "Xuan Jian"); Weaponmap.put ("Second", "Kong Tong Printing"); Weaponmap.put ("Third", "Nu wa shi"); 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=NewOutputStreamWriter (NewFileOutputStream ("success.html"), "UTF-8");               Template.process (Parammap, writer); System.out.println ("Congratulations, Build Success ~ ~"); } Catch(IOException e) {e.printstacktrace (); } Catch(templateexception e) {e.printstacktrace (); }         } } 

Five, Freemarker Custom label

I'll see you next time

Free Basic Concepts

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.