FreeMarker整合Springmvc

1 引用freddMarker jar包

<dependency>
	<groupId>org.freemarker</groupId>
	<artifactId>freemarker</artifactId>
</dependency>

2 在springmvc.xml文件中添加配置

	<!-- freeMarker整合 spring -->
	<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>

3 编写controller

package com.shi.item.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;

/**
 * 
 * @author: SHF
 * @date: 2018年3月27日 上午11:45:21
 * @Description:通过freemarker生成静态文件
 */
@Controller
public class freeMarkerHtml {
	
	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;
	
	@RequestMapping("/createItemHtml")
	@ResponseBody
	public String createItemHtml()throws Exception{
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		//1 加载模版对象
		Template template = configuration.getTemplate("hello.ftl");
		//2 创建一个数据集
		Map map=new HashMap();
		map.put("hello", "你好,小小小施爷!!");
		
		//3 指定文件输出的文件路径及文件集
		Writer out=new FileWriter(new File("C:/Users/shiye/Desktop/hello2.html"));
		
		//4 输出文件
		template.process(map, out);
		//5 关闭流
		out.close();
		
		return "ok";
	}
}

猜你喜欢

转载自my.oschina.net/u/3677987/blog/1785683