前面学习了Thymleaf和Velocity模板渲染,今天接触第三种模板渲染技术FreeMaker!
知识点预习:
- 通过PrintWriter out = resp.getWriter();可以获取输出流
- 依赖为freemarker
- 使用前需要获取其下的配置对象Configuration cfg
- 通过cfg.setDirectoryForTemplateLoading()读取模板文件目录
- 通过cfg.getTemplate("test.html")加载模板目录下指定名称的模板
- 渲染材料封装于Map中
- 通过template.process(material,out)将渲染数据后的页面响应给前端
- 通过FrameMaker渲染的模板不单单局限于html结构的文件,也可以是ftl后缀的文件
下面通过案例展示如何渲染两种格式模板的过程!
一.案例展示
1.测试准备
项目工程(maven下的webapp骨架)
2.代码展示
***pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
***test.ftl
我是${name},今年${age}岁,只有一个爱好就是${hobby}!
***test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>FrameMaker</title>
</head>
<body>
<#--注释的写法-->
<h1>${title}</h1>
<fieldset>
<span>${existPreMap.attention}</span>
<span>${existPreMap.message}</span>
</fieldset>
<fieldset>
多级变量获取省->市->区<br>
<span>${location.province.city.area}</span>
</fieldset>
<fieldset>
if的用法<br>
<span>
<#if sex==1><div>我是男人</div>
<#else><div>我是女人</div>
</#if>
</span>
</fieldset>
<fieldset>
switch的用法<br>
<span>
<#switch sex>
<#case 0>
I am girl!
<#break>
<#case 1>
I am boy!
<#break>
<#default>
I am nothing!
</#switch>
</span>
</fieldset>
<fieldset>
set集合<br>
<span><#list cities as city>${city},</#list></span><br>
</fieldset>
<fieldset>
list集合<br>
<span><#list names as name>${name},</#list></span><br>
</fieldset>
<fieldset>
数组<br>
<span><#list stars as star>${star},</#list><br>
数组加角标<br>
<span>${stars[0]}</span>
</fieldset>
<fieldset>
数值计算<br>
<#--加减乘除运算-->
<span>1+2/3=${1+2/3}</span>
<#--取整-->
<span>1+2/3=${(1+2/3)?int}</span>
</fieldset>
<fieldset>
<#--遍历list-->
<div>
<label>list</label>
<span>
<#list ["a","f","b"]+["aa","rr","cc"] as temp>
${temp},
</#list>
</span>
</div>
<#--加号连接两个哈希表,如果有重复的话,那么选择+号右侧的优先。注意<#assign只有头,没有结尾-->
<div>
<label>list</label>
<span>
<#assign ages={"Joe":21,"KK":33}+{"Joe":30,"BB":60}>
Joe:${ages.Joe}
BB:${ages.BB}
</span>
</div>
</fieldset>
</body>
</html>
***FTLServlet.java
package com.howie;
import freemarker.template.Configuration;
import freemarker.template.Template;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/**
* @Author weihuanwen
* @Date 2019/8/23 13:49
* @Version 1.0
*/
@WebServlet("/fs")
public class FTLServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//获取输出流
PrintWriter out = resp.getWriter();
//1.获取framemaker的配置对象
Configuration cfg=new Configuration();
cfg.setDefaultEncoding("UTF-8");
//2.获取项目根路径->指向classes
String path = FTLServlet.class.getResource("/").getPath();
//3.配置中添加项目模板文件夹
cfg.setDirectoryForTemplateLoading(new File(path+"template"));
//4.加载模板
Template template=cfg.getTemplate("test.ftl");
//5.封装渲染材料
Map map=new HashMap();
map.put("name","堂吉诃德");
map.put("age","99");
map.put("hobby","躺着");
//6.渲染模板并将渲染后的页面响应前端
template.process(map,out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
***HtmlServlet.java
package com.howie;
import freemarker.template.Configuration;
import freemarker.template.Template;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
/**
* @Author weihuanwen
* @Date 2019/8/23 14:17
* @Version 1.0
*/
@WebServlet("/hs")
public class HtmlServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//获取输出流
PrintWriter out = resp.getWriter();
//1.获取framemaker的配置对象
Configuration cfg=new Configuration();
cfg.setDefaultEncoding("UTF-8");
//2.获取项目根路径->指向classes
String path = FTLServlet.class.getResource("/").getPath();
//3.配置中添加项目模板文件夹
cfg.setDirectoryForTemplateLoading(new File(path+"template"));
//4.加载模板
Template template=cfg.getTemplate("test.html");
//5.封装渲染材料
Map material=new HashMap();
material.put("title", "FreeMaker");
Map existPreMap=new HashMap();
material.put("existPreMap", existPreMap);
existPreMap.put("attention", "请注意!");
existPreMap.put("message", "有消息!");
//设置所在地(多级变量)
Map area=new HashMap();
area.put("area", "西虹");
Map city=new HashMap();
city.put("city", area);
Map province=new HashMap();
province.put("province", city);
material.put("location", province);
//设置性别
material.put("sex",1);
//设置城市集合
Set cities=new TreeSet();
cities.add("河北");
cities.add("河南");
cities.add("河东");
cities.add("河西");
cities.add("南京");
cities.add("北京");
material.put("cities", cities);
//List
ArrayList names =new ArrayList();
names.add("Jhon");
names.add("Lily");
names.add("Smith");
names.add("Jack");
material.put("names", names);
//数组
String[] stars=new String[]{"☆","☆☆","☆☆☆"};
material.put("stars", stars);
//6.渲染模板并将渲染后的页面响应前端
template.process(material,out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
3.测试
①启动项目后访问请求路径:http://localhost:8080/fs,页面展示如下:
②继续访问请求路径:http://localhost:8080/hs,页面展示如下: