• FreeMarker配置详解


         首先需要添加freemarker.jar到项目,如果项目中有spring或者spirngmvc,需要整合,首先配置freemarkerConfig,代码结构如下:

            <!-- 设置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目录中

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

    然后freemarker用ftl文件来呈现视图,这时候就需要配置freemarker的视图解析器,代码如下:

            <!-- 配置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的视图,如果需要其他视图的解析器,可以自行添加。

           其中的exposeRequestAttributes  exposeSessionAttributes两个属性都被设置为true。结果是请求和会话属性都被复制到模板的属性集中,可以使用FreeMarker的表达式语言来访问并显示。

           使用这些宏,必须设置FreeMarkerViewResolver的exposeSpringMacroHelpers属性为true

    以上是freemarker与springmvc整合需要配置的xml文件。

    ------------------------------------------------------------------------------------------

    下面来介绍一下在Java 代码中如何使用:

        首先编写Freemarker的工具类,用来生成HTML文件的方法:

            

    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的各种语法跟标签。慢慢学习。。。

    【转载自】http://my.oschina.net/HuifengWang/blog/300461

  • 相关阅读:
    二分法查找
    全排列 递归实现 c 语言实现
    南阳oj 题目290 动物统计加强版 字典树
    蛇形填数
    南阳理工oj 题目289 苹果 01背包
    南阳理工 oj 题目38 布线问题
    南阳理工oj 题目85 有趣的数 Cantor数表
    CSU-1110 RMQ with Shifts (单点更新+区间最小值 zkw线段树)
    POJ-2387 Til the Cows Come Home
    HDU-2680 Choose the best route
  • 原文地址:https://www.cnblogs.com/dixinyunpan/p/5786942.html
Copyright © 2020-2023  润新知