1. 程式人生 > >javaEE Freemarker模板引擎,Freemarker與Spring的整合,生成靜態頁面

javaEE Freemarker模板引擎,Freemarker與Spring的整合,生成靜態頁面

applicationContext.xml(Spring配置檔案):

<?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-4.2.xsd
		http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

	<!-- 配置freemarker -->
	<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>

HtmlGenController.java(SpringMVC的Controller,通過Freemarker生成靜態頁面):

package cn.xxx.controller;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

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

//生成靜態頁面測試Controller
@Controller
public class HtmlGenController {

	@Autowired
	//注入freeMarkerConfigurer
	private FreeMarkerConfigurer freeMarkerConfigurer;
	
	@RequestMapping("/genhtml")
	@ResponseBody
	public String genHtml() throws Exception {
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		//載入模板物件
		Template template = configuration.getTemplate("hello.ftl");
		//建立一個數據集
		Map data = new HashMap<>();
		data.put("hello", 123456);
		//指定檔案輸出的路徑及檔名
		Writer out = new FileWriter(new File("D:/freemarker/hello.html"));
		//輸出檔案
		template.process(data, out);
		//關閉流
		out.close();
		
		return "OK";
	}
}

WEB-INF/ftl/hello.ftl(模板檔案):

${hello}