FreeMarker is a template engine developed in Java and is a general tool for generating text based on templates. It is designed to generate HTML web pages, especially applications based on MVC pattern. Although using FreeMarker requires some programming ability, Java programs usually prepare the data to be displayed, FreeMarker generates the page, and displays the prepared data through a template.
/
public void process(String template, Map<String, ?> data) throws Exception { Configuration cfg = new Configuration(); (new File("ftl")); (new DefaultObjectWrapper()); //Set the character set ("UTF-8"); //Set angle bracket syntax and square bracket syntax, default is automatic detection syntax // Automatic AUTO_DETECT_TAG_SYNTAX // Angle brackets ANGLE_BRACKET_TAG_SYNTAX // Square brackets SQUARE_BRACKET_TAG_SYNTAX (Configuration.AUTO_DETECT_TAG_SYNTAX); Writer out = new OutputStreamWriter(new FileOutputStream(FILE_DIR + template + ".txt"),"UTF-8"); Template temp = (template); (data, out); (); }
0. Use freemarker to create HelloWord web pages
Create a new WEB project and import it. Create a new folder templates under WEB-INF for storing templates. Create a new template file under templates. This is a sample template file. The content is HTML content, with a tag that is used to replace variables in the future, and the content is as follows:
<html> <head> <title>freemarkertest</title> </head> <body> <h1>${message},${name}</h1> </body> </html>
Create a new Servlet to request settings of variables and process the output of the template:
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; @SuppressWarnings("serial") public class HelloFreeMarkerServlet extends HttpServlet { // Responsible for managing the Configuration instance of the FreeMarker template private Configuration cfg = null; public void init() throws ServletException { // Create a FreeMarker instance cfg = new Configuration(); // Specify the location of the FreeMarker template file (getServletContext(), "/WEB-INF/templates"); } @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create a data model Map root = new HashMap(); ("message", "hello world"); ("name", "Java Xiaoqiang"); // Get the template file Template t = (""); // Use the template file's Charset as the charset of this page // Use text/html MIME-type ("text/html; charset=" + ()); Writer out = (); // Merge the data model and templates and output the results to out try { (root, out); // Write data into the template } catch (TemplateException e) { (); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void destroy() { (); } }
Note that you need to configure the Servlet in your:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="/xml/ns/javaee" xmlns:xsi="http:///2001/XMLSchema-instance" xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>hello</servlet-name> <servlet-class> </servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file></welcome-file> </welcome-file-list> </web-app>
To facilitate testing, access the project, jump directly to the Servlet and make a simple modification to the homepage:
<%@ page language="java" import=".*" pageEncoding="UTF-8"%> <% String path = (); String basePath = ()+"://"+() +":"+()+path+"/"; %> <html> <body> <% String mypath = "hello"; (basePath + mypath); %> </body> </html>
Deploy the project to Tomcat, start and access http://localhost:8080/f, the project name I created here is f.
1. Calculation formula
<#-- 1. Arithmetic operations -->[BR]${3 + 4} <#-- 2. Built-in function -->[BR]${"rensanning"?upper_case}
2. Output a value
HashMap t2root = new HashMap<String, String>(); ("user", "RenSanNing"); ${user}, Welcome!
3. Output a list
Map<String, Object> t3root = new HashMap<String, Object>(); List<Food> menu = new ArrayList<Food>(); (new Food("iText in Action", 98)); (new Food("iBATIS in Action", 118)); (new Food("Lucene in Action", 69)); ("menu", menu); <#list menu as food> ${} ${?} </#list>
4. Logical judgment (IF, SWITCH)
Map<String, Object> t4root = new HashMap<String, Object>(); ("x", 2); ("y", "medium");
<1>if, else, elseif: <#if x == 1> x is 1 <#elseif x == 2> x is 2 <#elseif x == 3> x is 3 <#elseif x == 4> x is 4 <#else> x is not 1 nor 2 nor 3 nor 4 </#if> <2>switch, case, default, break: <#switch y> <#case "small"> This will be processed if it is small <#break> <#case "medium"> This will be processed if it is medium <#break> <#case "large"> This will be processed if it is large <#break> <#default> This will be processed if it is neither </#switch> <3>list, break: <#assign seq = ["winter", "spring", "summer", "autumn"]> <#list seq as x> ${x_index + 1}. ${x}<#if x_has_next>,</#if> </#list>
5. Custom functions
<#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 variables -->[BR]<#function partg n lst> <#local ans = []> <#list lst as x> <#if (x >= n)> <#local ans = ans + [x]> </#if> </#list> <#return ans> </#function> <#assign ls = [10, 2, 4, 5, 8, 1, 3]> <#list partg(4, ls) as x>${x} </#list> <#-- 2. Variable domain test -->[BR]<#macro test> 03. ${x} <#global x = "global2"> 04. ${x} <#assign x = "assign2"> 05. ${x} <#local x = "local1"> 06. ${x} <#list ["Loop 1"] as x> 07. ${x} <#local x = "local2"> 08. ${x} <#assign x = "assign3"> 09. ${x} </#list> 10. ${x} </#macro> <#global x = "global1" /> 01. ${x} <#assign x = "assign1" /> 02. ${x} <@test /> 11. ${x}
7. Define macro macro
<#-- 1. No parameters -->[BR]<#macro greet> Welcome! </#macro> <@greet /> <#-- 2. There are parameters -->[BR]<#macro greet user> ${user}, Welcome! </#macro> <@greet user="RenSanNing"/> <#-- 3. There are multiple parameters -->[BR]<#macro table cols rows> <table> <#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. Bounce out in the middle -->[BR]<#macro out> Show text <#return> 不Show text </#macro> <@out /> <#-- 5. Nesting -->[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 the", "land of Medetai"] />
8、include
<#include ""> ${url} <@greet name="rensanning" />
<#macro greet name> ${name}, Welcome! </#macro> <#assign url="/">
9. Name Space
<#import "" as my> <#assign url="/"> ${} <@ name="rensanning" /> ${url}
<#macro greet name> ${name}, Welcome! </#macro> <#assign url="/">
10. Custom directive
public class SystemDateDirective implements TemplateDirectiveModel { public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { Calendar cal = (); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); ().append((())); } } 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, TemplateDirectiveBody 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 = (); if (len != null) { (textCut(s, len, append)); } else { (s); } } }
....
Map<String, Object> t10root = new HashMap<String, Object>(); ("systemdate", new SystemDateDirective()); ("text_cut", new TextCutDirective());