【freemarker】maven web项目freemarker demo搭建

 

注(freemarker中文网):http://freemarker.foofun.cn/


 

1 构建maven web项目

2 引入freemarker依赖 pom.xml


 

 <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>

3 引入jeety插件 pom.xml


<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.1.v20140609</version>
</plugin>

4 创建ftl文件 路径在webapp/temp下


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>新闻内容</title>
</head>
<body>

<h1>${titel}</h1>
<p>
新闻来源:${source}&nbsp; &nbsp; 发布时间: ${publishTime?string("yyyy-MM-dd")}
</p>
<p>
${content}
</p>
</body>
</html>

5 创建java文件继承 HttpServlet


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

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.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/news")
public class newsServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

// 得到模板
Configuration configuration = new Configuration();
configuration.setServletContextForTemplateLoading(getServletContext(),"/temp");
configuration.setDefaultEncoding("UTF-8");
Template template = configuration.getTemplate("news.ftl");


Map<String, Object> map = new HashMap<>();
map.put("source","中国知识网");
map.put("titel","小帅锅诞生");
map.put("publishTime",new Date());
map.put("content","在最佳情况下,你不需要使用这些内建函数");

// 生成html文件
String realPath = req.getServletContext().getRealPath("/html/");
File newsFile = new File(realPath);
if (newsFile.exists()) {
newsFile.mkdir();
}
// set name
String fileName = System.currentTimeMillis() + ".html";
File file = new File(realPath,fileName);
//
FileWriter writer = new FileWriter(file);
try {
template.process(map, writer);
} catch (TemplateException e) {
e.printStackTrace();
}
}
}

6 启动项目访问


http://localhost:8080/html/1621158840763.html
备注:1621158840763.html 文件java代码生成的文件


posted @ 2021-05-16 21:17  RonnieChen  阅读(431)  评论(0)    收藏  举报