First go to freemarker official website to download the source jar package, this article is based on freemarker-2.3.21.tar.gz research. Unzip the source package and find the Freemarker source part into the Eclipse project. Note that: The Freemarker FTL file parsing is implemented using JAVACC, so there is no parsing class (Fmparse.java) in the source code. To study Freemarker source code, often also need to introduce Freemarker.jar (containing fmparse.class), otherwise the source code will appear compile problems.
In addition, the jar packages that need to be introduced are: Commons-logging.jar,log4j.jar,servlet-api.jar. Finally, set the output of the log, so that we see the bottom running situation. The contents of the Log4j.properties file are as follows:
Log4j.rootlogger=debug,a1,a2
#指定log输出目的, this is set as the output log in the file My.Log of the specified directory
Log4j.appender.a1=org.apache.log4j.fileappender
Log4j.appender.a1.file=logs/my.log
#指定日志信息的格式
Log4j.appender.a1.layout=org.apache.log4j.patternlayout
log4j.appender.a1.layout.conversionpattern=%c[%d]-%m%n
#把A2输出到控制台
Log4j.appender.a2=org.apache.log4j.consoleappender
Log4j.appender.a2.layout=org.apache.log4j.patternlayout
log4j.appender.a2.layout.conversionpattern=[%c][%d][%p]-%m%n
Getting Started instance
First in the project to establish the folder templates template, and then into the template file Person.ftl, the following:
Hello, my name is ${name}. I come from ${address}. Nice to meet you!
| 1234567891011121314151617 |
public class Test {Public static void main(String[] args) Throws IOException, templateexception { Version version = new version (2, 3 , 1) Configuration Span class= "crayon-v" >cfg = new configuration ( version) cfg setdirectoryfortemplateloading (new file ( "templates" cfg setobjectwrapper (new defaultobjectwrapper ( Version Template temp = cfg. GetTemplate("PERSON.FTL"); Map root = new HashMap(); root. Put("name", "Zhang San"); root. Put("Address", "China-Beijing"); Writer out = new outputstreamwriter(System. Out); temp. Process(root, out ); Out . Flush(); }} |
The output is:
Hello, my name is Zhang three. I come from China-Beijing. Nice to meet you!
Freemarker Getting Started example and source research preparation work