Freemarker实现网页静态化

什么是freemarker?

FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表

现层的实现技术,而且还可以用于生成XML,JSP或Java 等。

目前企业中:主要用Freemarker做静态页面或是页面展示

Freemarker的使用方法:

Maven工程添加依赖:

<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.23</version>
</dependency>
原理:



使用步骤:

第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。

第二步:设置模板文件所在的路径。

第三步:设置模板文件使用的字符集。一般就是utf-8.

第四步:加载一个模板,创建一个模板对象。

第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。

第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。

第七步:调用模板对象的process方法输出文件。

第八步:关闭流。

        @Test
	public void genFile() throws Exception {
		// 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。
		Configuration configuration = new Configuration(Configuration.getVersion());
		// 第二步:设置模板文件所在的路径。
		configuration.setDirectoryForTemplateLoading(new File("D:/workspaces/demo/com-demo/src/main/webapp/WEB-INF/ftl"));
		// 第三步:设置模板文件使用的字符集。一般就是utf-8.
		configuration.setDefaultEncoding("utf-8");
		// 第四步:加载一个模板,创建一个模板对象。
		Template template = configuration.getTemplate("hello.ftl");
		// 第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。
		Map dataModel = new HashMap<>();
		//向数据集中添加数据
		dataModel.put("hello", "this is my first freemarker test.");
		// 第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。
		Writer out = new FileWriter(new File("D:/workspaces/demo/out/hello.html"));
		// 第七步:调用模板对象的process方法输出文件。
		template.process(dataModel, out);
		// 第八步:关闭流。
		out.close();
	}
创建hello.ftl

${hello}
el表达式可以取到对应key的value值。

使用pojo生成一个模板:

1.创建student实体类:生成get,set,有参构造方法。

public class Student {

	private int id;
	private String name;
	private int age;
	private String address;
}
2.创建模板类

public class FreeMarkerTest {

	@Test
	public void testFreeMarker() throws Exception {
		//1、创建一个模板文件
		//2、创建一个Configuration对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		//3、设置模板文件保存的目录
		configuration.setDirectoryForTemplateLoading(new File("D:/workspaces/demo/demo-web/src/main/webapp/WEB-INF/ftl"));
		//4、模板文件的编码格式,一般就是utf-8
		configuration.setDefaultEncoding("utf-8");
		//5、加载一个模板文件,创建一个模板对象。
		Template template = configuration.getTemplate("student.ftl");
		//6、创建一个数据集。可以是pojo也可以是map。推荐使用map
		Map data = new HashMap<>();
		data.put("hello", "hello freemarker!");
		//创建一个pojo对象
		Student student = new Student(1, "小李", 18, "北京");
		data.put("student", student);
		//添加一个list
		List<Student> stuList = new ArrayList<>();
		stuList.add(new Student(1, "小李1", 18, "北京"));
		stuList.add(new Student(2, "小李2", 19, "北京"));
		stuList.add(new Student(3, "小李3", 20, "北京"));
		stuList.add(new Student(4, "小李4", 21, "北京"));
		data.put("stuList", stuList);
		//添加日期类型
		data.put("date", new Date());
		//null值的测试
		data.put("val", "123");
		//7、创建一个Writer对象,指定输出文件的路径及文件名。
//		Writer out = new FileWriter(new File("D:/temp/demo/freemarker/hello.txt"));
		Writer out = new FileWriter(new File("D:/temp/demo/freemarker/student.html"));
		//8、生成静态页面
		template.process(data, out);
		//9、关闭流
		out.close();
	}
}

3.在WEB_INF下的ftl目录创建student.ftl(这里有一些模板的使用方法,后面不再介绍)

</head>
<body>
	学生信息:<br>
	学号:${student.id}    
	姓名:${student.name}    
	年龄:${student.age}    
	家庭住址:${student.address}<br>
	学生列表:
	<table border="1">
		<tr>
			<th>序号</th>
			<th>学号</th>
			<th>姓名</th>
			<th>年龄</th>
			<th>家庭住址</th>
		</tr>
		<#list stuList as stu>
		<#if stu_index % 2 == 0>
		<tr bgcolor="red">
		<#else>
		<tr bgcolor="green">
		</#if>
			<td>${stu_index}</td>
			<td>${stu.id}</td>
			<td>${stu.name}</td>
			<td>${stu.age}</td>
			<td>${stu.address}</td>
		</tr>
		</#list>
	</table>
	<br>
	<!-- 可以使用?date,?time,?datetime,?string(parten)-->
	当前日期:${date?string("yyyy/MM/dd HH:mm:ss")}<br>
	null值的处理:${val!"val的值为null"}<br>
	判断val的值是否为null:<br>
	<#if val??>
	val中有内容
	<#else>
	val的值为null
	</#if>
	引用模板测试:<br>
	<#include "hello.ftl">
</body>
</html>

Freemarker整合spring:

1.引入jia包

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context-support</artifactId>
</dependency>
2.配置springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<bean id="freemarkerConfig"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
		<property name="defaultEncoding" value="UTF-8" />
	</bean>
</beans>
3.需要编写一Controller进行测试

请求的url:/genhtml

参数:无

返回值:ok (String, 需要使用@ResponseBody)

@Controller
public class HtmlGenController {
	
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;

	@RequestMapping("/genhtml")
	@ResponseBody
	public String genHtml()throws Exception {
		// 1、从spring容器中获得FreeMarkerConfigurer对象。
		// 2、从FreeMarkerConfigurer对象中获得Configuration对象。
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		// 3、使用Configuration对象获得Template对象。
		Template template = configuration.getTemplate("hello.ftl");
		// 4、创建数据集
		Map dataModel = new HashMap<>();
		dataModel.put("hello", "1000");
		// 5、创建输出文件的Writer对象。
		Writer out = new FileWriter(new File("D:/temp/demo/out/spring-freemarker.html"));
		// 6、调用模板对象的process方法,生成文件。
		template.process(dataModel, out);
		// 7、关闭流。
		out.close();
		return "OK";
	}
}

Freemarker+nginx+Activemq:解决高并发

分析:

1.当高并发时,如果当用户访问时才创建模板,很容易模板没有创建完成,就会有用户去访问,这样就会造成页面内容不完整。

2.当生成模板过多,和高并发时,tomcat显然不适合当作访问的容器。

3.生成模板的名字不能重复。

解决方案:

1.当添加信息时,就要生成一个对应的模板,而不是访问页面时创建模板。

2.使用nginx同样可以访问静态资源,而且也可以解决高并发的问题,同时又解决了高可用。

3.用生成的唯一id作为名字,保证唯一id+.html。
















































  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值