如何在項目裏面使用freemarker實現頁面緩存(三)

1.環境配置:在這裏我就不說了,上面兩篇有如何配置freemarker

2.在項目裏面你運用freemarker需要在項目裏面創建一個模板文件夾,在web-inf下面創建一個ftl文件夾

3.由於通過freemarker將模板頁面轉化爲html頁面,前臺訪問直接跳頁面就行了,所以不能把生成的html文件放入web-inf文件夾下面,在webapp下創建一個文件夾命名html

4.寫service方法

4.1由於該方法需要交給spring統一管理,所以需要注入到spring裏面

4.2創建一個接口StaticPageService

import java.util.Map;

public interface StaticPageService {
	
	public void productIndex(Map<String, Object> root,Integer id);

}

4.3創建接口的實現類

public class StaticPageServiceImpl implements StaticPageService,ServletContextAware{
	
	private Configuration configuration;

	public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
		this.configuration = freeMarkerConfigurer.getConfiguration();
	}
	//靜態化方法
	public void productIndex(Map<String, Object> root,Integer id){
		//輸出流 從內存中寫入磁盤
		Writer out=null;
		//創建模板
		try {
			//讀入utf-8的數據到內存裏面
			Template template = configuration.getTemplate("productDetail.html");
			String path=getPath("/html/product/"+id+".html");
			File file=new File(path);
			File parentFile = file.getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			out=new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
			//模板對象處理
			template.process(root, out);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			//釋放io流
			if (out!=null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}
		
		
	}
	//獲取上下文路徑
	public String getPath(String name){
		
		return servletContext.getRealPath(name);
	}
	private ServletContext servletContext;

	
	public void setServletContext(ServletContext servletContext) {
		this.servletContext=servletContext;
		
	}

}


注意:由於要獲取模板文件夾的路徑

需要實現ServletContextAware接口重寫裏面的setServletContext方法,本service是使用set方式手動注入的。

root爲要填充頁面的數據。

4.4在spring配置文件裏面注入

<!-- 配置freemarker -->
     <bean id="staticPageService" class="cn.itcast.core.service.staticpage.StaticPageServiceImpl">
     		<property name="freeMarkerConfigurer">
     			<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
     				<!-- 設置模板路徑 -->
     				<property name="templateLoaderPath" value="/WEB-INF/ftl/"></property>
     				<!-- 設置控制模板爲utf-8 -->
     				<property name="defaultEncoding" value="UTF-8"></property>
     			</bean>
     		</property>
     </bean>

注意:這兩個參數必須傳


4.5 就是模板了,要將所有的標籤根據freemarker的語法轉化正確,由於free marker支持el表達式就不用轉化

例如:

<#list skus as sku>
	if("${sku.colorId}"==colorId && size=='${sku.size}'){
		//賦值
		$("#price").html("¥"+'${sku.skuPrice}');
		$("#mprice").html("¥"+'${sku.marketPrice}');
		$("#free").html('${sku.deliveFee}');
		$("#stock").html('${sku.stockInventory}');
		skuId='${sku.id}';
		buyLimit='${sku.skuUpperLimit}';
}
</#list>


啓動程序看相應文件夾生成相應的html文件了沒有。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章