freemarker靜態化的一個簡單示例

freemarker靜態化關鍵在於public void process(Object dataModel, Writer out) 方法。html

演示環境:springMVC+springjava

在spring中注入freemarker配置web

<bean id="freeMarkerConfigurer"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPaths" value="/WEB-INF"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">10</prop>
                <prop key="defaultEncoding">UTF-8</prop>
                <prop key="url_escaping_charset">UTF-8</prop>
                <prop key="locale">zh_CN</prop>
                <prop key="boolean_format">true,false</prop>
                <prop key="time_format">HH:mm:ss</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="date_format">yyyy-MM-dd</prop>
                <prop key="number_format">#.##</prop>
                <prop key="whitespace_stripping">true</prop>
            </props>
        </property>
    </bean>
/**
	 * freemarker靜態化示例
	 */
	@RequestMapping("freemarkerStatic")
	public void freemarkerStatic()
	{
		String templatePath = "d:/file.html";//靜態化頁面輸出路徑

		Map<String, String> staticDatas = new HashMap<String, String>();//待靜態化數據
		staticDatas.put("title", "freemarker靜態化示例");
		staticDatas.put("name", "小明");
		staticDatas.put("act", "說");
		staticDatas.put("content", "這是freemarker靜態化的一個簡單實例");

		Configuration cfg = freeMarkerConfigurer.getConfiguration();//獲得靜態化配置
		try
		{
			Template template = cfg.getTemplate("demo.ftl");//獲得模板(Configuration中配置爲WEB-INF根目錄下)
			File file = new File(templatePath);
			Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");//包裝文件輸入流爲輸出流
			template.process(staticDatas, out);//靜態化關鍵方法
			IOUtils.closeQuietly(out);//關閉輸出流
		}
		catch (TemplateException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

運行截圖,能夠在d盤下找到file.html文件spring

頁面內容爲api

相關文章
相關標籤/搜索