A basic tutorial for Freemarker Web Template development using Java _java

Source: Internet
Author: User

I. Overview

Freemarker is a template engine, a generic tool for generating text output based on templates, using pure Java authoring, Freemarker is designed to generate HTML Web pages, especially applications based on MVC patterns, although Freemarker has some programming capabilities , but typically the Java program prepares the data to be displayed, the page is generated by Freemarker, and the prepared data is displayed through the template (figure below)

Freemarker is not a Web application framework and is suitable as a component of 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 more appropriate as a view component of a MODEL2 framework such as Struts. You can also use the JSP tag library in the template. In addition, the Freemarker is free.

Ii. conditions for preparation of Freemarker

Freemarker.2.3.16.jar, download the address is not posted here. (This jar bag is actually inside the 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 label is mainly for iterative server-side pass over the list collection, such as:

  < #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:

  for (String names:namelist) { 
    System.out.println (names); 
  } 

2, if: The label is mainly to do if the use of, for example:

  < #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:

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


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

  < #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):

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

Actual code:

  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 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 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 (); 

 } 
       
    } 
  }


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 and end tags can never be the same line, or they will be an 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:

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


The following is the parsing class for the static.html template above:

  Package com.chenghui.test; 
   
  Import static Freemarker.template.ObjectWrapper.DEFAULT_WRAPPER; 
  Import java.io.IOException; 
  Import Java.io.Writer; 
   
   
  Import Java.util.Map; 
  Import freemarker.core.Environment; 
  Import Freemarker.template.TemplateDirectiveBody; 
  Import Freemarker.template.TemplateDirectiveModel; 
  Import freemarker.template.TemplateException; 
  Import Freemarker.template.TemplateModel; 
  Import freemarker.template.TemplateModelException; 
  Import Freemarker.template.TemplateNumberModel; 
   
  Import Freemarker.template.TemplateScalarModel; /** * Custom Label Resolution class * @author Administrator */public class Contentdirective implements Templatedirectivem 
    odel{private static final String Param_name = "NAME"; 
     
    private static final String param_age = "Age"; @Override public void execute (Environment env, MAP params,templatemodel[] loopvars, Templatedirectivebody bo DY) throws Templateexception,IOException {if (body==null) {throw new templatemodelexception ("null Body"); 
        }else{String name = getString (param_name, params); 
        Integer age = getInt (param_age, params); 
        After you receive the parameters, you can follow the specific action and then display the data in the page again. 
        if (name!=null) {env.setvariable ("Output", Default_wrapper.wrap ("The parameter obtained from the Contentdirective parsing class is:" +name+ ",")); 
        } if (Age!=null) {env.setvariable ("append", Default_wrapper.wrap ("Age:" +age)); 
        } Writer out = Env.getout (); Out.write ("The output from here can be seen on the page, just like the Document.writer write operation.") 
        <br/> "); 
         
        Body.render (out); 
        * If careful, will find the page is displayed out.write () output statements, and then output content, visible in the body in the parsing will first put the parameters in the Env, the page encountered the corresponding form when it will go to the value 
        However, if the form does not exist, it will be an error, I think the freemarker is not done here, parsing the time will be more to expose the error on the page. Can make up for this ${output! " 
        Null "}, always feel as good as not having an El expression. */}/** * Gets the value of a string type parameter * @param paramname * @param paRammap * @return * @throws templatemodelexception/public static string getString (String Paramnam E, map<string, templatemodel> parammap) throws templatemodelexception{Templatemodel model = parammap.get (par 
      Amname); 
      if (model = = NULL) {return null; 
      } if (model instanceof Templatescalarmodel) {return (Templatescalarmodel) model). Getasstring (); 
      }else if (model instanceof Templatenumbermodel) {return ((Templatenumbermodel) model). Getasnumber (). toString (); 
      }else{throw new Templatemodelexception (paramname); 
     /** * * Gets an int type parameter * @param paramname * @param parammap * @return * @throws templatemodelexception */public static Integer getInt (String paramname, map<string, Templatemodel 
      > Parammap) throws templatemodelexception{Templatemodel model = Parammap.get (paramname); if (model==null) {REturn null; 
        } if (model instanceof Templatescalarmodel) {String str = ((Templatescalarmodel) model). Getasstring (); 
        try {return integer.valueof (str); 
        catch (NumberFormatException e) {throw new templatemodelexception (paramname); }}else if (model instanceof Templatenumbermodel) {return ((Templatenumbermodel) model). Getasnumber (). intval 
      UE (); 
      }else{throw new Templatemodelexception (paramname); 

 } 
    } 
  }

And then add in the actual code above:

  Custom Label parsing 
  parammap.put ("Content", new contentdirective ()); 

This can be used basically, freemarker to complete the custom tag, to solve a simple business logic, but in the actual project can not do this, because it has not been integrated with spring, each time you need to parse the instance of the parse class into the.

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.