1. 程式人生 > >商城專案中使用freemarker生成靜態頁面html

商城專案中使用freemarker生成靜態頁面html

本部落格介紹,指定條件下生成靜態html頁面,生成後,網站不再訪問jsp頁面,而是訪問html.

舉例:一個商場購物網站,商品上架時候,傳送商品id到activeMQ,生成靜態頁面伺服器監聽activeMQ訊息,並生成靜態頁面,後續多個伺服器訪問產品詳情時候,不再需要進jsp,只需要跳到對應的html即可。

另freemark簡單使用方法:匯入freemarker-2.3.16.jar,見附件:http://download.csdn.net/download/w20228396/10262877

下面結合具體商城案例使用:

1、製作靜態模板

對於原產品詳情的jsp頁面進行改寫,去掉c標籤,部分標籤換為freemarker的標籤,如:遍歷用

<#list persons as person>
	${person_index}  ${person} <br/>
</#list>

引入其他頁面,如上下左右等邊角頁面用

<#include "commons/footer.html" />

加入UTF-8

<meta charset="UTF-8">

2、編寫freemarker.xml配置檔案,放在生成靜態頁面的專案中

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.0.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/task
   		http://www.springframework.org/schema/task/spring-task-4.0.xsd
		http://code.alibabatech.com/schema/dubbo        
		http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
		
		<!--靜態化的服務  -->
		<bean id="staticPageService" class="cn.dapeng.core.service.staticpage.StaticPageServiceImpl">
			<!-- 驅springmvc提供的freemarkerConfigurer -->
			<!-- 可以把bean寫到property裡一層,也可以通過ref引入 -->
			<property name="freeMarkerConfigurer">
				<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
					<!-- 設定模板所在資料夾 -->
					<property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
					<!-- 設定預設編碼 -->
					<property name="defaultEncoding" value="UTF-8"/>
				</bean>
			</property>
		</bean>
</beans>

3、產品上架時,需要將產品的ID群發給各個伺服器,這裡產品的service配置改為主題

<bean id="jmsTempalte" class="org.springframework.jms.core.JmsTemplate">
			<!-- 注入Spring的工廠 -->
			<property name="connectionFactory" ref="connectionFactory"/>
			<!--  JmsTempalte操作某個通道,把通道名稱給它,即配置預設目標:商品id 如果用其他目標則jmsTemplate.send(destination, messageCreator)-->
			<property name="defaultDestinationName" value="productId"/>
			<!--預設不設定是佇列 ; 設定就是傳送主題 -->
			<property name="pubSubDomain" value="true"/>
		</bean>

4、生成靜態頁面的專案中,需要監聽器,監聽activeMQ傳送過來的產品ID,編寫mq.xml,配置監聽類,配置接收訊息為主題

		<!-- 訊息處理類 -->
		<bean id="customMessageListener" class="cn.dapeng.core.mq.CustomMessageListener"/>
		
		
		<!--Spring監聽MQ 沒人需要調它,沒人需要注入他,所以不要id -->
		<bean class="org.springframework.jms.listener.DefaultMessageListenerContainer">
			<!--1、連線Mq進行監聽  -->
			<property name="connectionFactory" ref="connectionFactory"/>
			<!--2、監聽的目標地點  -->
			<property name="destinationName" value="productId"/>
			<!--3、接收訊息  -->
			<property name="messageListener" ref="customMessageListener"/>
			<!--4、預設不設定是佇列 ; 設定就是傳送主題  -->
			<property name="pubSubDomain" value="true"/>
		</bean>
5、生成靜態頁面的專案中,監聽類CustomMessageListener,監聽得到產品ID,並且根據id查出詳情列表需要的資訊,然後放到root中。
public class CustomMessageListener implements MessageListener {

	@Autowired
	private StaticPageService staticPageService;
	@Autowired
	private CmsService cmsService;
	
	@Override
	public void onMessage(Message message) {
		// TODO Auto-generated method stub
		ActiveMQTextMessage aMessage = (ActiveMQTextMessage) message;
		
		try {
			String productId = aMessage.getText();
			System.out.println("cms:"+productId);
			//資料模型
			Map<String, Object> root = new HashMap<>();
			// 查詢商品
			Product product = cmsService.selectProductById(Long.parseLong(productId));
			// 查詢庫存
			List<Sku> skus = cmsService.selectSkuListByProductId(Long.parseLong(productId));
			// 去掉顏色重複
			Set<Color> colors = new HashSet<Color>();
			for (Sku sku : skus) {
				colors.add(sku.getColor());
			}
			root.put("product", product);
			root.put("skus", skus);
			root.put("colors", colors);
			
			staticPageService.productStaticPage(root, productId);
			//solrService.
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
6、staticPageService的實現類中生成對應產品的靜態頁面
 * 靜態化服務類
 * @author Administrator
 *
 */
public class StaticPageServiceImpl implements StaticPageService,ServletContextAware{

	//宣告(注入 freeMarkerConfigurer 得到 conf)
	private Configuration conf;
	//private FreeMarkerConfigurer freeMarkerConfigurer;
	
	public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
		this.conf = freeMarkerConfigurer.getConfiguration();
	}

	//靜態化程式
	@Override
	public void productStaticPage(Map<String, Object> root, String id) {
		//獲取的絕對路徑E:\eclipse-micservice\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\
		// wtpwebapps\babasport-service-cms/html/product/12131313.html
		String path = getPath("/html/product/"+id+".html");
		File f = new File(path);
		File parentFile = f.getParentFile();
		if (!parentFile.exists()) {
			parentFile.mkdirs();
		}
		//載入目錄下指定的模板檔案
		Writer out = null;
		try {
			//讀取模板(UTF-8)
			Template template = conf.getTemplate("productDetail.html");
			//輸入流  寫UTF-8
			out = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
			// 處理process
			template.process(root, out);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if (null != out) {
					out.close();
				} 
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	// 獲取專案應用的路徑
	public String getPath(String name) {
		return servletContext.getRealPath(name);
	}
	//宣告
	private ServletContext servletContext;
	@Override
	public void setServletContext(ServletContext servletContext){
		this.servletContext = servletContext;
	}
}
7、靜態頁面生成後,修改連結地址,點選詳情頁面跳轉到對應的靜態頁面
<div class="p-name p-name-type-2">
    <a title="滿129立減10,199減20優惠券,支援貨到付款" href="javascript:;" onclick="window.open('http://localhost:8084/html/product/${product.id}.html')">
        <em>${product.name }</em>
    </a>
</div>
8、結束,啟動專案去驗證