Freemarker页面静态化

什么是Freemarker?

Freemarker是一款使用java写的模板引擎,它基于模板来生成文本输出.它虽然不是web的应用框架,因为FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或Http,但它很适合作为web应用框架的一个组件.它不仅可以用作表现层的实现技术,而且还可以用于生成XML.JSP.JAVA等

特点:

1.轻量级模板引擎,不需要Servlet环境就可以很轻松的嵌入到应用程序中.
2.能生成各种文本,如html.xml.java等
3.入门简单,它是用java编写的.很多语法和java相似.
工作原理的话是:模板+数据==输出 == 就是Freemarker 可以输出到指定的位置,生成一个完成的页面.
在这里插入图片描述

Freemarker的作用?

自定义框架
自定义代码生成器.

创建模板文件:模板文件中四种元素
  1.文本,直接输出的部分
  2.注释.即<#–…-->格式不会输出
  3.插值(Interpolation):即${…}部分,将使用数据模型中的部分替代输出
  4.FTL指令:FreeMarker指令,和HTML标记类似,名字前家#予以区分,不会输出.
test.ftl

<html>
<head>
	<meta charset="utf-8">
	<title>Freemarker入门小DEMO </title>
</head>
<body>

<#--我只是一个注释,我不会有任何输出  -->
${name},你好。${message}

<h3>assigne指令</h3>
<#assign linkman="周先生">
联系人:${linkman}

<#assign info={"mobile":"13301231212",'address':'北京市昌平区王府街'} >
电话:${info.mobile}  地址:${info.address}

<h3>if指令</h3>
<#if success=true>
  你已通过实名认证
<#else>  
  你未通过实名认证
</#if>

<h3>list指令</h3>
----商品价格表----<br>
<#list goodsList as goods>
  ${goods_index+1} 商品名称: ${goods.name} 价格:${goods.price}<br>
</#list>

<h3>内建函数</h3>
<h4>获取集合大小</h4>
共  ${goodsList?size}  条记录

<h4>转换JSON字符串为对象</h4>
    <#assign text="{'bank':'工商银行','account':'10101920201920212'}" />
	<#assign data=text?eval />
	开户行:${data.bank}  账号:${data.account}
	
<h4>日期格式化</h4>
当前日期:${today?date} <br>
当前时间:${today?time} <br>   
当前日期+时间:${today?datetime} <br>        
日期格式化:  ${today?string("yyyy年MM月")}

<h4>数字转换为字符串</h4>
累计积分:${point}
累计积分:${point?c}


<h3>空值处理运算符</h3>
<h4>判断某变量是否存在:“??”</h4>
<#if aaa??>
  aaa变量存在
<#else>
  aaa变量不存在
</#if>

<h4>缺失变量默认值:“!”</h4>
  ${aaa!'-'}


<h3>运算符</h3>
<h4>算数运算符</h4>
FreeMarker表达式中完全支持算术运算,FreeMarker支持的算术运算符包括:+, - , * , / , %

<h4>逻辑运算符</h4>
逻辑运算符有如下几个: 
逻辑与:&& 
逻辑或:|| 
逻辑非:! 
逻辑运算符只能作用于布尔值,否则将产生错误 

<h4>比较运算符</h4>
表达式中支持的比较运算符有如下几个: 
1  =或者==:判断两个值是否相等. 
2  !=:判断两个值是否不等. 
3  >或者gt:判断左边值是否大于右边值 
4  >=或者gte:判断左边值是否大于等于右边值 
5  <或者lt:判断左边值是否小于右边值 
6  <=或者lte:判断左边值是否小于等于右边值 
注意:  =和!=可以用于字符串,数值和日期来比较是否相等,但=和!=两边必须是相同类型的值,否则会产生错误,而且FreeMarker是精确比较,"x","x ","X"是不等的.其它的运行符可以作用于数字和日期,但不能作用于字符串,大部分的时候,使用gt等字母运算符代替>会有更好的效果,因为 FreeMarker会把>解释成FTL标签的结束字符,当然,也可以使用括号来避免这种情况,

</body>
</html>

demo1
将可以写死的数据都定死,而像时间之类就生成我们想要的静态 html 页面

package com.javaxl.freemarker;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Demo001 {
	public static void main(String[] args) throws IOException, TemplateException {
		// 1.创建配置类
		Configuration configuration = new Configuration(Configuration.getVersion());
		// 2.设置模板所在的目录
		configuration.setDirectoryForTemplateLoading(
				new File("D:\\temp\\lucene\\T224\\javaxl_lunece_freemarker\\src\\main\\resources"));
		// 3.设置字符集
		configuration.setDefaultEncoding("utf-8");
		// 4.加载模板
		Template template = configuration.getTemplate("test.ftl");
		// 5.创建数据模型
		Map map = new HashMap();
		map.put("name", "小李飞刀 ");
		map.put("message", "欢迎来到神奇的博客网站:http://www.javaxl.com!");
		map.put("success", true);
		
		List goodsList=new ArrayList();
		Map goods1=new HashMap();
		goods1.put("name", "苹果");
		goods1.put("price", 5.8);
		Map goods2=new HashMap();
		goods2.put("name", "香蕉");
		goods2.put("price", 2.5);
		Map goods3=new HashMap();
		goods3.put("name", "橘子");
		goods3.put("price", 3.2);
		goodsList.add(goods1);
		goodsList.add(goods2);
		goodsList.add(goods3);
		map.put("goodsList", goodsList);
		
		map.put("today", new Date());
		map.put("point", 102920122);
		
		// 6.创建Writer对象
		Writer out = new FileWriter(new File("D:\\temp\\lucene\\T224\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker\\test.html"));
		// 7.输出
		template.process(map, out);
		// 8.关闭Writer对象
		out.close();
	}
}

在这里插入图片描述

package com.javaxl.freemarker;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.javaxl.blog.util.DBAccess;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Demo002 {
	@SuppressWarnings("rawtypes")
	public static void main(String[] args) throws IOException, TemplateException, SQLException {
		// 1.创建配置类
		Configuration configuration = new Configuration(Configuration.getVersion());
		// 2.设置模板所在的目录
		configuration.setDirectoryForTemplateLoading(
				new File("D:\\temp\\lucene\\T224\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker"));
		// 3.设置字符集
		configuration.setDefaultEncoding("utf-8");
		// 4.加载模板
		Template template = configuration.getTemplate("blogDetail.ftl");
		
		
		// 5.创建数据模型
//		Map map = new HashMap();
//		map.put("name", "小李飞刀 ");
//		// 6.创建Writer对象
//		Writer out = new FileWriter(new File("E:\\temp\\staticPage\\test.html"));
//		// 7.输出
//		template.process(map, out);
		// 8.关闭Writer对象
//		out.close();
		createPage(template);
		
	}
	
	private static void createPage(Template template) throws SQLException, IOException, TemplateException {
		Connection con = DBAccess.getConnection();
		String sql = "select * from t_lucene_freemarker_blog";
		PreparedStatement pst = con.prepareStatement(sql);
		ResultSet rs = pst.executeQuery();
		Map map = new HashMap<>();
		Map<String, Object> blog = new HashMap<>();
		while(rs.next()) {
			blog.put("bid", rs.getObject("bid"));
			blog.put("title", rs.getObject("title"));
			blog.put("releaseDate", rs.getObject("releaseDate"));
			blog.put("btid", rs.getObject("btid"));
			blog.put("clickHit", rs.getObject("clickHit"));
			blog.put("content", rs.getObject("content"));
			
			map.put("blog", blog);
//			// 6.创建Writer对象
			Writer out = new FileWriter(new File("D:\\temp\\lucene\\T224\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker\\"+blog.get("bid")+".html"));
			// 7.输出
			template.process(map, out);
			// 8.关闭Writer对象
			out.close();
		}
		DBAccess.close(con, pst, rs);
	}
}

demo2
通过数据库里数据用createPage方法生成静态页面,点链接进去就不需要进入后台

package com.javaxl.freemarker;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.javaxl.blog.util.DBAccess;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Demo002 {
	@SuppressWarnings("rawtypes")
	public static void main(String[] args) throws IOException, TemplateException, SQLException {
		// 1.创建配置类
		Configuration configuration = new Configuration(Configuration.getVersion());
		// 2.设置模板所在的目录
		configuration.setDirectoryForTemplateLoading(
				new File("D:\\temp\\lucene\\T224\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker"));
		// 3.设置字符集
		configuration.setDefaultEncoding("utf-8");
		// 4.加载模板
		Template template = configuration.getTemplate("blogDetail.ftl");
		
		
		// 5.创建数据模型
//		Map map = new HashMap();
//		map.put("name", "小李飞刀 ");
//		// 6.创建Writer对象
//		Writer out = new FileWriter(new File("E:\\temp\\staticPage\\test.html"));
//		// 7.输出
//		template.process(map, out);
		// 8.关闭Writer对象
//		out.close();
		createPage(template);
		
	}
	
	private static void createPage(Template template) throws SQLException, IOException, TemplateException {
		Connection con = DBAccess.getConnection();
		String sql = "select * from t_lucene_freemarker_blog";
		PreparedStatement pst = con.prepareStatement(sql);
		ResultSet rs = pst.executeQuery();
		Map map = new HashMap<>();
		Map<String, Object> blog = new HashMap<>();
		while(rs.next()) {
			blog.put("bid", rs.getObject("bid"));
			blog.put("title", rs.getObject("title"));
			blog.put("releaseDate", rs.getObject("releaseDate"));
			blog.put("btid", rs.getObject("btid"));
			blog.put("clickHit", rs.getObject("clickHit"));
			blog.put("content", rs.getObject("content"));
			
			map.put("blog", blog);
//			// 6.创建Writer对象
			Writer out = new FileWriter(new File("D:\\temp\\lucene\\T224\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker\\"+blog.get("bid")+".html"));
			// 7.输出
			template.process(map, out);
			// 8.关闭Writer对象
			out.close();
		}
		DBAccess.close(con, pst, rs);
	}
}

后台jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form
		action="${pageContext.request.contextPath}/sy/freemarkerBlog_list.action"
		method="post">
		博客标题:<input type="text" name="title"> <input type="submit"
			value="确定">
	</form>
	<button id="add">添加</button>
	<button id="refresh">刷新全局索引</button>
	<table border="1" width="100%" cellspacing="0">
		<tr>
			<td>编号</td>
			<td>标题</td>
			<td>内容</td>
			<td>操作</td>
		</tr>
		<c:forEach items="${blogList }" var="blog">
			<tr>
				<td>${blog.bid }</td>
				<td>${blog.title }</td>
				<!-- 不使用网页静态化 -->
				<%-- <td><a target="_blank" href="${pageContext.request.contextPath}/sy/freemarkerBlog_show.action?bid=${blog.bid }">${blog.summary }</a></td>
 --%>				<!-- 使用网页静态化 -->
				<td><a target="_blank" href="${pageContext.request.contextPath}/freemarker/${blog.bid }.html">${blog.summary }</a></td>
				<td><a href="">修改</a> <a href="">删除</a></td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值