springmvc使用freemarker

首先須要添加freemarker.jar到項目,若是項目中有spring或者spirngmvc,須要整合,首先配置freemarkerConfig,代碼結構以下html

<!-- 設置freeMarker的配置文件路徑 -->
    <bean id="freemarkerConfiguration"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:freemarker.properties" />
    </bean>


        <bean id="freemarkerConfig"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="freemarkerSettings" ref="freemarkerConfiguration" /> 
        <property name="templateLoaderPath">
            <value>/WEB-INF/freemarker/</value>
        </property>
        <property name="freemarkerVariables"><!--設置一些經常使用的全局變量-->
            <map>
            <entry key="xml_escape" value-ref="fmXmlEscape" />
            <entry key="webRoot" value="/shop"></entry>  
                        <entry key="jsRoot" value="/shop/js"></entry>   
            </map>
        </property>
    </bean>

其中一下代碼是用來掃描.ftl的模板文件,在/web-info/freemarker目錄中java

<property name="templateLoaderPath">
    <value>/WEB-INF/freemarker/</value>
</property>

而後freemarker用ftl文件來呈現視圖,這時候就須要配置freemarker的視圖解析器,代碼以下:web

<!-- 配置freeMarker視圖解析器 -->
    <bean id="freemarkerViewResolver"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" 
            />
        <property name="viewNames" value="*.ftl" />
        <property name="contentType" value="text/html; charset=utf-8" />
        <property name="cache" value="true" />
        <property name="suffix" value="" />
    <!--     <property name="exposeRequestAttributes" value="true" />
        <property name="exposeSessionAttributes" value="true" />
        <property name="exposeSpringMacroHelpers" value="true" /> -->
        <property name="order" value="0" />
    </bean>
    <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加先後綴 通用解析器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="" />
        <property name="viewNames" value="*.html,*.jsp" />
        <property name="suffix" value="" />
        <property name="viewClass"
            value="org.springframework.web.servlet.view.InternalResourceView" />
        <property name="order" value="1"></property>
    </bean>

 其中:<property name="order" value="0">表明了第一個匹配的是freemarker的視圖解析器,若是匹配不成功,則自動選擇order=1的其餘解析器,目前的通用解析器能夠解析.html跟.jsp的視圖,若是須要其餘視圖的解析器,能夠自行添加。spring

       其中的exposeRequestAttributes  exposeSessionAttributes兩個屬性都被設置爲true。結果是請求和會話屬性都被複制到模板的屬性集中,能夠使用FreeMarker的表達式語言來訪問並顯示。mvc

       使用這些宏,必須設置FreeMarkerViewResolver的exposeSpringMacroHelpers屬性爲trueapp

以上是freemarker與springmvc整合須要配置的xml文件。jsp

------------------------------------------------------------------------------------------工具

 

下面來介紹一下在Java 代碼中如何使用:學習

    首先編寫Freemarker的工具類,用來生成HTML文件的方法ui

package com.hc.shop.common.tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

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

/**
 * @author HuifengWang 靜態化方法
 **/
public class FreeMarkerUtil {
    /**
     * 
     * 生成HTML靜態頁面的公公方法
     * @param fmc 
     * @param templateName 模板的名稱
     * @param request
     * @param map 生成模板須要的數據
     * @param filePath 相對於web容器的路徑
     * @param fileName 要生成的文件的名稱,帶擴展名
     * @author HuifengWang
     * 
     */
    public static void createHtml(FreeMarkerConfig fmc, String templateName,
            HttpServletRequest request, Map<?, ?> map, String filePath,
            String fileName) {
        Writer out = null;
        try {
            Template template = fmc.getConfiguration()
                    .getTemplate(templateName);
            String htmlPath = request.getSession().getServletContext()
                    .getRealPath(filePath)
                    + "/" + fileName;
            File htmlFile = new File(htmlPath);
            if (!htmlFile.getParentFile().exists()) {
                htmlFile.getParentFile().mkdirs();
            }
            if (!htmlFile.exists()) {
                htmlFile.createNewFile();
            }
            out = new OutputStreamWriter(new FileOutputStream(htmlPath),"UTF-8");
            template.process(map, out);
            out.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                out = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    /**
     * @param request
     * @param filePath  文件存放的路徑
     * @param fileName 文件的名稱,須要擴展名
     * @author HuifengWang
     * @return
     */
    public static Map<String,Object> htmlFileHasExist(HttpServletRequest request,String filePath,
            String fileName) {
        Map<String,Object> map = new HashMap<String,Object>();
        String htmlPath = request.getSession().getServletContext()
                .getRealPath(filePath)
                + "/" + fileName;
        File htmlFile = new File(htmlPath);
        if(htmlFile.exists()){
            map.put("exist", true);
        }else{
            map.put("exist",false);
        }
        return map ;
    }
}

以上就是要生成HTML文件的工具類,參數註解都有,應該很好理解。

 

如何在Controller中調用??下面來看一個很簡單的demo

@Autowired
    private FreeMarkerConfig freeMarkerConfig;//獲取FreemarkerConfig的實例
    
    @RequestMapping("/ttt")
    public String ttt(HttpServletRequest request,HttpServletResponse response,ModelMap mv) throws IOException, TemplateException, ServletException{
        String fileName ="ttt.html";
        Boolean flag =(Boolean)FreeMarkerUtil.htmlFileHasExist(request, FREEMARKER_PATH, fileName).get("exist");
        if(!flag){//如何靜態文件不存在,從新生成
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("user", "xiaowang小王");//這裏包含業務邏輯請求等
            mv.addAllAttributes(map);
            FreeMarkerUtil.createHtml(freeMarkerConfig, "demo.ftl", request, map, FREEMARKER_PATH, fileName);//根據模板生成靜態頁面
        }
        return FREEMARKER_PATH+"/"+fileName;//始終返回生成的HTML頁面
    }

以上就是如何在springmvc中使用Freemarker的具體實現方式,想要很好的瞭解,會用,熟悉Freemarker,還須要瞭解Freemarker的各類語法跟標籤。慢慢學習。。。