Freemarker is a Java-developed template engine that is a general-purpose tool for generating text based on templates. It is designed to generate HTML Web pages, especially applications based on the MVC pattern. While using Freemarker requires some programming power, the Java program typically prepares the data to be displayed, generates pages from Freemarker, and displays the prepared data through a template.
http://freemarker.org/
public void process (String template, map<string,?> data) throws Exception {
Configuration cfg = new Configurati On ();
Cfg.setdirectoryfortemplateloading (New File ("FTL"));
Cfg.setobjectwrapper (New Defaultobjectwrapper ());
Sets the character set
cfg.setdefaultencoding ("UTF-8");
Set angle bracket syntax and bracket syntax, default is automatic detection of syntax//
automatic auto_detect_tag_syntax
//Angle bracket angle_bracket_tag_syntax
//square brackets Square_ Bracket_tag_syntax
Cfg.settagsyntax (configuration.auto_detect_tag_syntax);
Writer out = new OutputStreamWriter (new FileOutputStream (File_dir + template + ". txt"), "UTF-8");
Template temp = cfg.gettemplate (Template);
Temp.process (data, out);
Out.flush ();
}
0, use Freemarker to make Helloword Web page
Create a new Web project and import Freemarker.jar, create a new folder under Web-inf to store template files, create a new TEST.FTL under Templates, which is a sample template file. Content is HTML content, with a marker inside it for future variable substitution, as follows:
Creates a new servlet that requests the settings variable and processes the stencil output:
Package com.test.servlet;
Import java.io.IOException;
Import Java.io.Writer;
Import Java.util.HashMap;
Import Java.util.Map;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import freemarker.template.Configuration;
Import Freemarker.template.Template;
Import freemarker.template.TemplateException; @SuppressWarnings ("Serial") public class Hellofreemarkerservlet extends HttpServlet {//Freemarker for managing Configuratio templates
n instance private Configuration cfg = null;
public void Init () throws Servletexception {//Create a Freemarker instance cfg = new Configuration ();
Specifies the location of the Freemarker template file Cfg.setservletcontextfortemplateloading (Getservletcontext (), "/web-inf/templates");
@SuppressWarnings ("unchecked") public void DoPost (HttpServletRequest request, httpservletresponse response) Throws Servletexception, IOException {// Establish the data model MAP root = new HashMap ();
Root.put ("message", "Hello World");
Root.put ("name", "Java Cockroach");
Gets the template file Template t = cfg.gettemplate ("TEST.FTL"); Use the charset of the template file as the charset//use text/html mime-type response.setcontenttype ("text/html;
charset= "+ t.getencoding ());
Writer out = Response.getwriter (); Merge data models and templates, and output the results to try {t.process (root, out) in out;//write data to templates} catch (Templateexception e) {e.
Printstacktrace (); } public void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex
ception {doPost (request, response);
public void Destroy () {Super.destroy ();
}
}
Note that you want to configure the servlet in your web.xml:
<?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "2.5" xmlns= "http://java.sun.com/xml/ns/"
Java ee "
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "
xsi:schemalocation=" http://java.sun.com/ Xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">
<servlet>
< servlet-name>hello</servlet-name>
<servlet-class>
Com.test.servlet.HelloFreeMarkerServlet
</servlet-class>
</servlet>
< servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</ url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file> index.jsp</welcome-file>
</welcome-file-list>
</web-app>
To facilitate testing, visit the project directly to the servlet, make a simple change to the homepage index.jsp:
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<%
String Path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername ()
+ ":" +request.getserverport () +path+ "/";
%>
Deploy engineering to Tomcat, start up and access http://localhost:8080/f, the project name I built here is F.
1. Calculation type
<#--1, arithmetic operations-->[BR]
${3 + 4}
<#--2, built-in function-->[BR]
${"rensanning"? Upper_case}
2, output a value
HashMap t2root = new hashmap<string, string> ();
T2root.put ("User", "rensanning");
${user}, welcome!
3, output a list
map<string, object> t3root = new hashmap<string, object> ();
list<food> menu = new Arraylist<food> ();
Menu.add (New Food ("IText in Action",);
Menu.add (New Food ("IBATIS in Action", 118));
Menu.add (New Food ("Lucene in Action",);
T3root.put ("menu", menu);
< #list menu as food>
${food.name} ${food.price?string.currency}
</#list >
4. Logical Judgment (If,switch)
map<string, object> t4root = new hashmap<string, object> ();
T4root.put ("X", 2);
T4root.put ("Y", "medium");
<1>if, Else, ElseIf:
< #if x = = 1>
x is 1
< #elseif x = = 2>
x is 2
< #elseif x = = 3& gt;
X is 3
< #elseif x = = 4>
x is 4
< #else > x was not
1 nor 2 nor 3 nor 4
</#if >
&l T;2>switch, case, default, break:
< #switch y>
< #case "small" > This would be
processed if it is small
< #break >
< #case "Medium" > This'll be
processed if it is medium
< #break >
< #case "Large" > This'll be
processed if it is large
< #break >
< #default >< C24/>this'll be processed if it's neither
</#switch >
<3>list, Break:
< #assign seq = [WI Nter "," Spring "," Summer "," Autumn "]>
< #list seq as x>
${x_index + 1}. ${x}< #if x_has_next> </#if >
</#list >
5. Custom Function
< #function fact N>
< #if n = 0>
< #return 1/>
< #else >
< #return fact (n-1) * n />
</#if >
</#function >
< #list 0..10 as i>
${i}! =>-${fact (i)}
</# List>
6. Define Variables
<#--1, local variable-->[BR]
< #function partg n lst>
< #local ans = []>
< #list lst as x>
&L T #if (x >= N) >
< #local ans = ans + [x]>
</#if >
</#list >
< #return ans>
</#function >
< #assign ls = [2, 4, 5, 8, 1, 3]>
< #list partg (4, LS) as x>${x} </#li St>
<#--2, variable domain test-->[BR]
< #macro test>
${x}
< #global x = "Global2" >
${x}
< #assign x = "Assign2" >
${x}
< #local x = "Local1" >
modified ${x}
< #list ["Cycle 1"] as x>
${x}
< #local x = "Local2" >
${x}
< #assign x = "Assign3" ;
${X}
</#list >
${x}
</#macro >
< #global x = "Global1"/>
-${x}
< #assign x = "Assign1"/>
${x}
< @test/>
${x}
7. Define Macro Macro
<#--1, no parameters-->[BR] < #macro greet> welcome!
</#macro > < @greet/> <#--2, Parameters-->[BR] < #macro greet user> ${user}, welcome! </#macro > < @greet user= "rensanning"/> <#--3, has multiple parameters-->[BR] < #macro table cols rows> <tab Le> < #list 1..rows as row> <tr> < #list 1..cols as Col> <td>${row}, ${col}< /TD> </#list > </tr> </#list > </table> </#macro > < @table cols=3 rows=2
/> <#--4, Middle jump-->[BR] < #macro out> display text < #return > do not display text </#macro > < @out/> <#--5, nested-->[BR] < #macro lprint lst> < #list lst as item> ${item}< #nested item/> </# List> </#macro > < @lprint 1..3; x>^2 = ${x * x}</@lprint > < @lprint 1..3;
x>^3 = ${x * x * x}</@lprint > < @lprint ["Let's Go", "to", "Land of Medetai"]/>
8, include
< #include "T108INCLUDE.FTL" >
${url}
< @greet name= "rensanning"/>
T108include.ftl
< #macro greet name>
${name}, welcome!
</#macro >
< #assign url= "http://www.baidu.com/" >
9. Name Space
< #import "T109INCLUDE.FTL" as my>
< #assign url= "http://www.google.com/" >
${my.url}
< @my. Greet name= "rensanning"/>
${url}
T109include.ftl
< #macro greet name>
${name}, welcome!
</#macro >
< #assign url= "http://www.baidu.com/" >
10. custom Directive Directive
public class Systemdatedirective implements Templatedirectivemodel {public void execute (Environment env, MAP para MS, templatemodel[] loopvars, templatedirectivebody body) throws Templateexception, IOException {Calendar cal
= Calendar.getinstance ();
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy/mm/dd HH:mm:ss");
Env.getout (). Append (Sdf.format (Cal.gettime ()));
} public class Textcutdirective implements Templatedirectivemodel {public static final String param_s = "S";
public static final String Param_len = "LEN";
public static final String param_append = "APPEND"; @SuppressWarnings ("unchecked") public void execute (Environment env, MAP params, templatemodel[] Loopvars, Templa
Tedirectivebody body) throws Templateexception, IOException {String s = getString (param_s, params);
Integer len = getInt (Param_len, params);
String append = getString (param_append, params); if (s!= null) {Writer out =Env.getout ();
if (len!= null) {Out.append (Textcut (S, Len, append));
else {out.append (s);
}
}
}
....
map<string, object> t10root = new hashmap<string, object> ();
T10root.put ("Systemdate", New Systemdatedirective ());
T10root.put ("Text_cut", New Textcutdirective ());