什么是网页静态化
首先让我们说说什么是网页静态化:
FreeMarker 是一个用 Java 语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与 Web 容器无关,即在 Web 运行时,它并不知道 Servlet 或 HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成 XML,JSP 或 Java 等。
为什么要用网页静态化
然后是为什么要用网页静态化:
一、减轻服务器负担,浏览网页无需调用系统数据库。
二、有利于搜索引擎优化SEO,Baidu、Google都会优先收录静态页面,不仅被收录的快还收录的全;
三、加快页面打开速度,静态页面无需连接数据库打开速度较动态页面有明显提高;
四、网站更安全,HTML页面不会受php程序相关漏洞的影响;观看一下大一点的网站基本全是静态页面,而且可以减少攻击,防sql注入。数据库出错时,不影响网站正常访问。
五、数据库出错时,不影响网站的正常访问。
就是一些固定内容比较多的一些网站,例如博客、文章等等,除了了内容、标题作者等等,其他网页的模块都是定死的,那么在这些网站上你想要提高性能,就可以使用网页静态化
案例:
demo1:
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("E:\\Demo\\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("E:\\Demo\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker\\test.html"));
// 7.输出
template.process(map, out);
// 8.关闭Writer对象
out.close();
}
}
test.html:
<html>
<head>
<meta charset="utf-8">
<title>Freemarker入门小DEMO </title>
</head>
<body>
小李飞刀 ,你好。欢迎来到神奇的博客网站:http://www.javaxl.com!
<h3>assigne指令</h3>
联系人:周先生
电话:13301231212 地址:北京市昌平区王府街
<h3>if指令</h3>
你已通过实名认证
<h3>list指令</h3>
----商品价格表----<br>
1 商品名称: 苹果 价格:5.8<br>
2 商品名称: 香蕉 价格:2.5<br>
3 商品名称: 橘子 价格:3.2<br>
<h3>内建函数</h3>
<h4>获取集合大小</h4>
共 3 条记录
<h4>转换JSON字符串为对象</h4>
开户行:工商银行 账号:10101920201920212
<h4>日期格式化</h4>
当前日期:2019-9-10 <br>
当前时间:0:09:17 <br>
当前日期+时间:2019-9-10 0:09:17 <br>
日期格式化: 2019年09月
<h4>数字转换为字符串</h4>
累计积分:102,920,122
累计积分:102920122
<h3>空值处理运算符</h3>
<h4>判断某变量是否存在:“??”</h4>
aaa变量不存在
<h4>缺失变量默认值:“!”</h4>
-
<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>
项目运用:
blogDao:
package com.javaxl.blog.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.javaxl.blog.util.JsonBaseDao;
import com.javaxl.blog.util.PageBean;
import com.javaxl.blog.util.StringUtils;
public class BlogDao extends JsonBaseDao{
public List<Map<String,Object>> list(String title, PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_lucene_crawler_blog where 1=1";
if(StringUtils.isNotBlank(title)) {
sql += " and title like '%"+title+"%'";
}
return super.executeQuery(sql, pageBean);
}
public int save(Map<String,String[]> paMap) throws InstantiationException, IllegalAccessException, SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException{
String sql = "insert into t_lucene_crawler_blog values(?,?,?,?,0)";
return super.executeUpdate(sql, new String[] {"id","title","content","url"}, paMap);
}
public List<Map<String,Object>> freemarker_list(String title, PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_lucene_freemarker_blog where 1=1 ";
if(StringUtils.isNotBlank(title)) {
sql += " and title like '%"+title+"%'";
}
return super.executeQuery(sql, pageBean);
}
public List<Map<String,Object>> freemarker_show(String bid) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_lucene_freemarker_blog where bid = "+bid;
return super.executeQuery(sql, null);
}
}
FreemarkerBlogAction:
package com.javaxl.blog.web;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.store.Directory;
import org.apache.struts2.ServletActionContext;
import com.javaxl.blog.dao.BlogDao;
import com.javaxl.blog.util.LuceneUtil;
import com.javaxl.blog.util.PropertiesUtil;
import com.javaxl.blog.util.StringUtils;
/**
* 专门将网页静态化的类,这里不涉及到lucene
* @author Administrator
*
*/
public class FreemarkerBlogAction {
private String title;
private String summary;
private String bid;
private BlogDao blogDao = new BlogDao();
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBid() {
return bid;
}
public void setBid(String bid) {
this.bid = bid;
}
public String list() throws ParseException, IOException, InvalidTokenOffsetsException {
HttpServletRequest request = ServletActionContext.getRequest();
try {
if(StringUtils.isBlank(title)) {
List<Map<String, Object>> blogList = this.blogDao.freemarker_list(title, null);
request.setAttribute("blogList", blogList);
}
else {
Directory directory = LuceneUtil.getDirectory(PropertiesUtil.getValue("indexPath2"));
DirectoryReader reader = LuceneUtil.getDirectoryReader(directory);
IndexSearcher searcher = LuceneUtil.getIndexSearcher(reader);
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
// 拿一句话到索引目中的索引文件中的词库进行关键词碰撞
Query query = new QueryParser("title",analyzer).parse(title);
Highlighter highlighter = LuceneUtil.getHighlighter(query, "title");
// Query query1 = new QueryParser("summary", analyzer).parse(title);
// Highlighter highlighter1 = LuceneUtil.getHighlighter(query1, "summary");
TopDocs topDocs = searcher.search(query , 100);
//处理得分命中的文档
List<Map<String, Object>> blogList = new ArrayList<>();
Map<String, Object> map = null;
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc : scoreDocs) {
map = new HashMap<>();
Document doc = searcher.doc(scoreDoc.doc);
map.put("bid", doc.get("bid"));
String titleHighlighter = doc.get("title");
// String sumHighlighter = doc.get("summary");
if(StringUtils.isNotBlank(titleHighlighter)) {
titleHighlighter = highlighter.getBestFragment(analyzer, "title", titleHighlighter);
}
// if(StringUtils.isNotBlank(sumHighlighter)) {
// sumHighlighter = highlighter1.getBestFragment(analyzer, "summary", sumHighlighter);
// map.put("summary", sumHighlighter);
// }
map.put("summary", doc.get("summary"));
map.put("title", titleHighlighter);
blogList.add(map);
}
request.setAttribute("blogList", blogList);
}
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
return "blogList";
}
public String show() {
HttpServletRequest request = ServletActionContext.getRequest();
try {
Map<String, Object> blog = this.blogDao.freemarker_show(bid).get(0);
request.setAttribute("blog", blog);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "blogDetail";
}
}
生成静态页面的demo:
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("E:\\Demo\\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("E:\\Demo\\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);
}
}
所需配置文件blogDetail.ftl:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!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>Python Django 模板层(AJAX)-javaxl-晓码阁-博客专栏</title>
<link rel="stylesheet" href="./freemarkerDemo_files/bootstrap.min.css">
<link rel="stylesheet"
href="./freemarkerDemo_files/bootstrap-theme.min.css">
<link rel="stylesheet" href="./freemarkerDemo_files/blog.css">
<script src="./freemarkerDemo_files/jquery-1.11.2.min.js.下载"></script>
<script src="./freemarkerDemo_files/bootstrap.min.js.下载"></script>
<style type="text/css">
body {
padding-top: 10px;
padding-bottom: 40px;
}
</style>
</head>
<body>
<div class="container">
<script type="text/javascript">
function checkData() {
var q = document.getElementById("q").value.trim();
if (q == null || q == "") {
alert("请输入您要查询的关键字!");
return false;
} else {
return true;
}
}
</script>
<div class="row">
<div class="col-md-12" style="padding-top: 10px">
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">展开</span> <span class="icon-bar"></span> <span
class="icon-bar"></span> <span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="http://www.javaxl.com/index"><b
style="color: black"><strong>首页</strong></b></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse"
id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="http://122.114.92.43/p4/index" target="_blank"><b
color="black"><strong>美食</strong></b></a></li>
<li><a href="http://59.110.212.17/p5/index" target="_blank"><b
color="black"><strong>知识库</strong></b></a></li>
<li><a href="http://www.javaxl.com/abortMe" target="_blank"><b
color="black"><strong>关于本站</strong></b></a></li>
</ul>
<form action="http://www.javaxl.com/admin/blog/q"
class="navbar-form navbar-right" role="search" method="post"
onsubmit="return checkData()">
<div class="form-group">
<input type="text" id="q" name="q" value="" class="form-control"
placeholder="请输入要查询的关键字...">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid --> </nav>
</div>
</div>
<div class="row" style="margin-top: 50px;">
<!--
真正展示博客内容的地方,
所有博客链接的列表->list.jsp
单条博客详情->view.jsp
呼和条件的博客详情列表->result.jsp
-->
<div class="col-md-9">
<script type="text/javascript"
src="./freemarkerDemo_files/shCore.js.下载"></script>
<link rel="stylesheet"
href="./freemarkerDemo_files/shCoreDefault.css">
<script type="text/javascript">
/*本页面用于查看博客链接中的详细内容*/
SyntaxHighlighter.all();
function showOtherComment() {
$(".otherComment").show();
}
function loadimage() {
document.getElementById("randImage").src = "/static/system/jsp/common/image.jsp?"
+ Math.random();
}
function submitData() {
var content = $("#content").val();
var imageCode = $("#imageCode").val();
if (content == null || content == "") {
alert("请输入评论内容!");
} else if (imageCode == null || imageCode == "") {
alert("请填写验证码!");
} else {
$.post("/comment/save.do", {
"content" : content,
'imageCode' : imageCode,
'blog.bid' : '323'
}, function(result) {
if (result.success) {
window.location.reload();
alert("评论已提成成功,审核通过后显示!");
} else {
alert(result.errorInfo);
}
}, "json");
}
}
</script>
<div class="data_list">
<div class="data_list_title">
<img
src="./freemarkerDemo_files/blog_show_icon.png" />
博客信息
</div>
<div>
<div class="blog_title">
<h3>
<strong>${blog.title }</strong>
</h3>
</div>
<div class="blog_share">
<!-- <div class="bshare-custom"><a title="分享到QQ空间" class="bshare-qzone"></a><a title="分享到新浪微博" class="bshare-sinaminiblog"></a><a title="分享到人人网" class="bshare-renren"></a><a title="分享到腾讯微博" class="bshare-qqmb"></a><a title="分享到网易微博" class="bshare-neteasemb"></a><a title="更多平台" class="bshare-more bshare-more-icon more-style-addthis"></a><span class="BSHARE_COUNT bshare-share-count">0</span></div><script type="text/javascript" charset="utf-8" src="http://static.bshare.cn/b/buttonLite.js#style=-1&uuid=&pophcol=2&lang=zh"></script><script type="text/javascript" charset="utf-8" src="http://static.bshare.cn/b/bshareC0.js"></script> -->
</div>
<div class="blog_info">发布时间:『${blog.releaseDate?datetime }』 博客类别:${blog.btid } 阅读(${blog.clickHit })
</div>
<div class="blog_content">${blog.content }</div>
</div>
</div>
</div>
<!-- 右侧布局 -->
<div class="col-md-3">
<div class="data_list">
<div class="data_list_title">博主信息</div>
<div class="user_image">
<img src="./freemarkerDemo_files/index_1.jpg">
</div>
<div class="nickName">javaxl_小李飞刀</div>
<div class="userSign">(知识改变命运,教育改变生活)</div>
</div>
<div class="data_list">
<div class="data_list_title">
<img src="./freemarkerDemo_files/byType_icon.png"> 按日志类别
</div>
<div class="datas">
<ul>
<li><span><a
href="http://www.javaxl.com/index.html?btid=9">java基础(71)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=1">自定义mvc(8)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=2">前端框架(39)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=4">索引框架(7)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=5">SSH(14)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=6">SSM(9)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=7">服务器部署(5)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=8">项目异常归总(5)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=10">安全框架(4)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=11">SpringBoot(15)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=12">程序人生(3)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=13">其他框架(5)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=14">开发工具(6)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=15">解决方案(7)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=16">23种设计模式(25)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=17">SpringCloud(14)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=18">第三方(4)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=19">Python(67)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?btid=20">底层探究(1)</a></span></li>
</ul>
</div>
</div>
<div class="data_list">
<div class="data_list_title">
<img src="./freemarkerDemo_files/byDate_icon.png"> 按日志日期
</div>
<div class="datas">
<ul>
<li><span><a
href="http://www.javaxl.com/index.html?releaseDateStr=2019%E5%B9%B408%E6%9C%88">2019年08月(36)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?releaseDateStr=2019%E5%B9%B407%E6%9C%88">2019年07月(27)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?releaseDateStr=2019%E5%B9%B406%E6%9C%88">2019年06月(47)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?releaseDateStr=2019%E5%B9%B405%E6%9C%88">2019年05月(61)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?releaseDateStr=2019%E5%B9%B404%E6%9C%88">2019年04月(18)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?releaseDateStr=2019%E5%B9%B403%E6%9C%88">2019年03月(50)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?releaseDateStr=2019%E5%B9%B402%E6%9C%88">2019年02月(57)</a></span></li>
<li><span><a
href="http://www.javaxl.com/index.html?releaseDateStr=2019%E5%B9%B401%E6%9C%88">2019年01月(13)</a></span></li>
</ul>
</div>
</div>
<div class="data_list">
<div class="data_list_title">
<img src="./freemarkerDemo_files/link_icon.png"> 友情链接
</div>
<div class="datas">
<ul>
<li><span><a href="http://www.baidu.com/"
target="_blank">百度</a></span></li>
<li><span><a href="http://122.114.92.43/p4/index"
target="_blank">晓码阁-美食网</a></span></li>
<li><span><a href="http://59.110.212.17/p5/index"
target="_blank">晓码阁-知识库</a></span></li>
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div align="center" style="padding: 20px">
<span style="float: left;">Powered by <a
href="http://www.javaxl.com/" target="_blank">博客首页</a> V1.0
</span> Copyright © 2018-2019 javaxl晓码阁 版权所有
</div>
</div>
</div>
</div>
</body>
</html>
也就是静态页面的模板
最后就是Jsp页面blogList.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>
然后是效果图:
lucene和网页静态化整合
lucene代码:
blogList.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/blog_list.action"
method="post">
博客标题:<input type="text" name="title"> <input type="submit"
value="确定">
</form>
<button id="add" onclick="javascript:window.location.href='${pageContext.request.contextPath}/add.jsp'">添加</button>
<button id="refresh" onclick="javascript:window.location.href='${pageContext.request.contextPath}/sy/blog_createIndex.action'">刷新全局索引</button>
<button id="refresh">刷新静态页面</button>
<table border="1" width="100%">
<tr>
<td>编号</td>
<td>名称</td>
<td>价格</td>
<td>操作</td>
</tr>
<c:forEach items="${blogList }" var="blog">
<tr>
<td>${blog.id }</td>
<td>${blog.title }</td>
<td><a href="${blog.url }">${blog.title }</a></td>
<td>
<a href="">修改</a>
<a href="${pageContext.request.contextPath}/sy/blog_del.action?id=${blog.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
add.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<h3>增加博客</h3>
<form action="${pageContext.request.contextPath}/sy/blog_add.action">
博客id:<input name="id" type="text" /><br/>
博客title:<input name="title" type="text" /><br/>
博客content:<input name="content" type="text" /><br/>
博客url:<input name="url" type="text" /><br/>
<input type="submit" />
</form>
</body>
</html>
BlogDao:
package com.javaxl.blog.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import com.javaxl.blog.util.JsonBaseDao;
import com.javaxl.blog.util.PageBean;
import com.javaxl.blog.util.StringUtils;
public class BlogDao extends JsonBaseDao{
public List<Map<String,Object>> list(String title, PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_lucene_crawler_blog where 1=1";
if(StringUtils.isNotBlank(title)) {
sql += " and title like '%"+title+"%'";
}
return super.executeQuery(sql, pageBean);
}
public int save(Map<String,String[]> paMap) throws InstantiationException, IllegalAccessException, SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException{
String sql = "insert into t_lucene_crawler_blog values(?,?,?,?,0)";
return super.executeUpdate(sql, new String[] {"id","title","content","url"}, paMap);
}
public int edit(Map<String,String[]> paMap) throws InstantiationException, IllegalAccessException, SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException{
String sql = "update t_lucene_crawler_blog set title=?,content=?,url=? where id=?";
return super.executeUpdate(sql, new String[] {"title","content","url","id"}, paMap);
}
public int del(Map<String,String[]> paMap) throws InstantiationException, IllegalAccessException, SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException{
String sql = "delete from t_lucene_crawler_blog where id=?";
return super.executeUpdate(sql, new String[] {"id"}, paMap);
}
public List<Map<String,Object>> freemarker_list(String title, PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_lucene_freemarker_blog where 1=1 ";
if(StringUtils.isNotBlank(title)) {
sql += " and title like '%"+title+"%'";
}
return super.executeQuery(sql, pageBean);
}
public List<Map<String,Object>> freemarker_show(String bid) throws InstantiationException, IllegalAccessException, SQLException{
String sql = "select * from t_lucene_freemarker_blog where bid = "+bid;
return super.executeQuery(sql, null);
}
}
blogAction:
package com.javaxl.blog.web;
import java.io.IOException;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.struts2.ServletActionContext;
import com.javaxl.blog.dao.BlogDao;
import com.javaxl.blog.util.LuceneUtil;
import com.javaxl.blog.util.PropertiesUtil;
import com.javaxl.blog.util.StringUtils;
import com.javaxl.freemarker.Demo002;
import freemarker.template.TemplateException;
/**
* IndexReader
* IndexSearcher
* Highlighter
* @author Administrator
*
*/
public class BlogAction {
private String id;
private String title;
private String content;
private String url;
private BlogDao blogDao = new BlogDao();
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String list() {
try {
HttpServletRequest request = ServletActionContext.getRequest();
Map<String, String[]> parameterMap = request.getParameterMap();
if (StringUtils.isBlank(title)) {
List<Map<String, Object>> blogList = this.blogDao.list(title, null);
request.setAttribute("blogList", blogList);
}else {
Directory directory = LuceneUtil.getDirectory(PropertiesUtil.getValue("indexPath"));
DirectoryReader reader = LuceneUtil.getDirectoryReader(directory);
IndexSearcher searcher = LuceneUtil.getIndexSearcher(reader);
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
Query query = new QueryParser("title", analyzer).parse(title);
Highlighter highlighter = LuceneUtil.getHighlighter(query, "title");
TopDocs topDocs = searcher.search(query , 100);
//处理得分命中的文档
List<Map<String, Object>> blogList = new ArrayList<>();
Map<String, Object> map = null;
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc : scoreDocs) {
map = new HashMap<>();
Document doc = searcher.doc(scoreDoc.doc);
map.put("id", doc.get("id"));
String titleHighlighter = doc.get("title");
if(StringUtils.isNotBlank(titleHighlighter)) {
titleHighlighter = highlighter.getBestFragment(analyzer, "title", titleHighlighter);
}
map.put("title", titleHighlighter);
map.put("url", doc.get("url"));
blogList.add(map);
}
request.setAttribute("blogList", blogList);
}
} catch (Exception e) {
e.printStackTrace();
}
return "blogList";
}
public String add() throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, IllegalArgumentException, SQLException {
HttpServletRequest req = ServletActionContext.getRequest();
Map<String, String[]> paMap = req.getParameterMap();
System.out.println(title+"tit");
int save = blogDao.save(paMap);
// 数据增加成功
if(save>0) {
System.out.println("增加成功");
// 新增索引
IndexWriterConfig conf = new IndexWriterConfig(new SmartChineseAnalyzer());
Directory d;
IndexWriter indexWriter = null;
try {
d = FSDirectory.open(Paths.get(PropertiesUtil.getValue("indexPath")));
indexWriter = new IndexWriter(d , conf );
Document doc = new Document();
doc.add(new StringField("id", id, Field.Store.YES));
doc.add(new TextField("title", title, Field.Store.YES));
doc.add(new TextField("content", content, Field.Store.YES));
doc.add(new StringField("url", url, Field.Store.YES));
System.out.println("添加索引成功");
// 新增静态页面
} catch (Exception e) {
e.printStackTrace();
}
return "blogList";
}
else {
System.out.println("增加失败");
return "blogList";
}
}
public String del() throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, IllegalArgumentException, SQLException {
HttpServletRequest req = ServletActionContext.getRequest();
int del = blogDao.del(req.getParameterMap());
if(del>0) {
System.out.println("删除成功");
return "blogList";
}
else {
System.out.println("删除失败");
return "blogList";
}
}
/**
* 刷新索引
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws SQLException
*/
public String createIndex() throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, IllegalArgumentException, SQLException {
IndexStarter index=new IndexStarter();
index.CreateIndex();
System.out.println("刷新索引成功");
return "blogList";
}
}
IndexStarter :
package com.javaxl.blog.web;
import java.io.IOException;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import com.javaxl.blog.dao.BlogDao;
import com.javaxl.blog.util.PropertiesUtil;
/**
* 构建lucene索引
* @author Administrator
* 1。构建索引 IndexWriter
* 2、读取索引文件,获取命中片段
* 3、使得命中片段高亮显示
*
*/
public class IndexStarter {
private static BlogDao blogDao = new BlogDao();
public static void main(String[] args) {
IndexWriterConfig conf = new IndexWriterConfig(new SmartChineseAnalyzer());
Directory d;
IndexWriter indexWriter = null;
try {
d = FSDirectory.open(Paths.get(PropertiesUtil.getValue("indexPath")));
indexWriter = new IndexWriter(d , conf );
// 为数据库中的所有数据构建索引
List<Map<String, Object>> list = blogDao.list(null, null);
for (Map<String, Object> map : list) {
Document doc = new Document();
doc.add(new StringField("id", (String) map.get("id"), Field.Store.YES));
doc.add(new TextField("title", (String) map.get("title"), Field.Store.YES));
doc.add(new StringField("url", (String) map.get("url"), Field.Store.YES));
indexWriter.addDocument(doc);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(indexWriter!= null) {
indexWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 刷新索引
*/
public void CreateIndex() {
IndexWriterConfig conf = new IndexWriterConfig(new SmartChineseAnalyzer());
Directory d;
IndexWriter indexWriter = null;
try {
d = FSDirectory.open(Paths.get(PropertiesUtil.getValue("indexPath")));
indexWriter = new IndexWriter(d , conf );
indexWriter.deleteAll();//删除所有索引
// 为数据库中的所有数据构建索引
List<Map<String, Object>> list = blogDao.list(null, null);
for (Map<String, Object> map : list) {
Document doc = new Document();
doc.add(new StringField("id", (String) map.get("id"), Field.Store.YES));
doc.add(new TextField("title", (String) map.get("title"), Field.Store.YES));
doc.add(new StringField("url", (String) map.get("url"), Field.Store.YES));
indexWriter.addDocument(doc);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(indexWriter!= null) {
indexWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
网页静态化代码
blogList.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" onclick="javascript:window.location.href='${pageContext.request.contextPath}/sy/freemarkerBlog_createIndex.action">刷新全局索引</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>
add.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<h3>增加博客</h3>
<form action="${pageContext.request.contextPath}/sy/freemarkerBlog_add.action">
博客title:<input name="title" type="text" /><br/>
博客summary:<input name="summary" type="text" /><br/>
<input type="submit" />
</form>
</body>
</html>
FreemarkerBlogAction:
package com.javaxl.blog.web;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.connector.Request;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.store.Directory;
import org.apache.struts2.ServletActionContext;
import com.javaxl.blog.dao.BlogDao;
import com.javaxl.blog.util.LuceneUtil;
import com.javaxl.blog.util.PropertiesUtil;
import com.javaxl.blog.util.StringUtils;
import com.javaxl.freemarker.Demo002;
import freemarker.template.TemplateException;
/**
* 专门将网页静态化的类,这里不涉及到lucene
* @author Administrator
*
*/
public class FreemarkerBlogAction {
private String title;
private String summary;
private String bid;
private BlogDao blogDao = new BlogDao();
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBid() {
return bid;
}
public void setBid(String bid) {
this.bid = bid;
}
public String list() throws ParseException, IOException, InvalidTokenOffsetsException {
HttpServletRequest request = ServletActionContext.getRequest();
try {
if(StringUtils.isBlank(title)) {
List<Map<String, Object>> blogList = this.blogDao.freemarker_list(title, null);
request.setAttribute("blogList", blogList);
}
else {
Directory directory = LuceneUtil.getDirectory(PropertiesUtil.getValue("indexPath2"));
DirectoryReader reader = LuceneUtil.getDirectoryReader(directory);
IndexSearcher searcher = LuceneUtil.getIndexSearcher(reader);
SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
// 拿一句话到索引目中的索引文件中的词库进行关键词碰撞
Query query = new QueryParser("title",analyzer).parse(title);
Highlighter highlighter = LuceneUtil.getHighlighter(query, "title");
// Query query1 = new QueryParser("summary", analyzer).parse(title);
// Highlighter highlighter1 = LuceneUtil.getHighlighter(query1, "summary");
TopDocs topDocs = searcher.search(query , 100);
//处理得分命中的文档
List<Map<String, Object>> blogList = new ArrayList<>();
Map<String, Object> map = null;
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc : scoreDocs) {
map = new HashMap<>();
Document doc = searcher.doc(scoreDoc.doc);
map.put("bid", doc.get("bid"));
String titleHighlighter = doc.get("title");
// String sumHighlighter = doc.get("summary");
if(StringUtils.isNotBlank(titleHighlighter)) {
titleHighlighter = highlighter.getBestFragment(analyzer, "title", titleHighlighter);
}
// if(StringUtils.isNotBlank(sumHighlighter)) {
// sumHighlighter = highlighter1.getBestFragment(analyzer, "summary", sumHighlighter);
// map.put("summary", sumHighlighter);
// }
map.put("summary", doc.get("summary"));
map.put("title", titleHighlighter);
blogList.add(map);
}
request.setAttribute("blogList", blogList);
}
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
return "blogList";
}
public String show() {
HttpServletRequest request = ServletActionContext.getRequest();
try {
Map<String, Object> blog = this.blogDao.freemarker_show(bid).get(0);
request.setAttribute("blog", blog);
} catch (InstantiationException | IllegalAccessException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "blogDetail";
}
public String add() throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, IllegalArgumentException, SQLException, IOException, TemplateException {
HttpServletRequest req = ServletActionContext.getRequest();
int save = blogDao.save(req.getParameterMap());
if(save>0) {
System.out.println("增加成功");
Demo002 demo02=new Demo002();
demo02.createPage();
System.out.println("静态页面创建成功");
}
return "blogList";
}
public String del() throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, IllegalArgumentException, SQLException {
HttpServletRequest req = ServletActionContext.getRequest();
int del = blogDao.del(req.getParameterMap());
if(del>0) {
System.out.println("删除成功");
}
return "blogList";
}
/**
* 刷新索引
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws SQLException
*/
public String createIndex() throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, IllegalArgumentException, SQLException {
IndexStarter2 index=new IndexStarter2();
index.CreateIndex();
System.out.println("刷新索引成功");
return "blogList";
}
}
Demo002:
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 com.javaxl.blog.util.JsonUtils;
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("E:\\Demo\\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("E:\\Demo\\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);
}
/**
* 增加单个静态页面
* @param template
* @throws SQLException
* @throws IOException
* @throws TemplateException
*/
private static void createSinglePage(Template template) throws SQLException, IOException, TemplateException {
Map<String, String[]> paMap=new HashMap<>();
String title = JsonUtils.getParamVal(paMap, "title");
String btid = JsonUtils.getParamVal(paMap, "btid");
String summary = JsonUtils.getParamVal(paMap, "summary");
Map map = new HashMap<>();
Map<String, Object> blog = new HashMap<>();
map.put("title", title);
map.put("btid", btid);
map.put("summary", summary);
// // 6.创建Writer对象
Writer out = new FileWriter(new File("E:\\Demo\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker\\"+blog.get("bid")+".html"));
// 7.输出
template.process(map, out);
// 8.关闭Writer对象
out.close();
}
public void createPage() throws IOException, SQLException, TemplateException {
// 1.创建配置类
Configuration configuration = new Configuration(Configuration.getVersion());
// 2.设置模板所在的目录
configuration.setDirectoryForTemplateLoading(
new File("E:\\Demo\\javaxl_lunece_freemarker\\src\\main\\webapp\\freemarker"));
// 3.设置字符集
configuration.setDefaultEncoding("utf-8");
// 4.加载模板
Template template = configuration.getTemplate("blogDetail.ftl");
createSinglePage(template);
}
}