java-使用 freemarker 替換 jstl EL 開發 springmvc web專案

草青工作室發表於2017-03-31
java-使用 freemarker 替換 jstl EL 開發 springmvc web專案


freemarker 是一款模板引擎,不限於 web 中,但與 springmvc 結合可以替換 jstl 的功能,且更加靈活。
資源:
freemarker 官網:http://freemarker.org/
官網提供了中文的手冊可以下載到本地看:
https://sourceforge.net/projects/freemarker/files/chinese-manual/


目標:
藉助springmvc 中 controller 向頁面傳值的模式,利用 freemarker 對頁面進行填充
藉助 org.springframework.ui.Model 物件或 Map 物件將資訊傳到 springmvc 的頁面中


需要:
1.freemarker 元件
2.springmvc 元件


1.建立專案名稱為 “mavers-web” 的maven web專案,新增 maven 新增依賴:
  <properties>
	<!-- 檔案拷貝時的編碼 -->
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	<!-- 編譯時的編碼 -->
	<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
	<org.springframework.version>4.3.7.RELEASE</org.springframework.version>
  </properties>
  <dependencies>
	<!-- spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-websocket</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-context-support</artifactId>
	    <version>${org.springframework.version}</version>
	</dependency>    
    <!-- jstl(jsp 標準標籤庫) -->
	<dependency>
	    <groupId>jstl</groupId>
	    <artifactId>jstl</artifactId>
	    <version>1.2</version>
	</dependency>
	<!-- freemarker 模板引擎 -->
	<dependency>
		<groupId>org.freemarker</groupId>
		<artifactId>freemarker</artifactId>
		<version>2.3.26-incubating</version>
	</dependency>
  </dependencies>



2.配置 spring 和 freemarker(需要配置三個xml)


2.1 web.xml 配置


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
	<display-name>Archetype Created Web Application</display-name>
	<listener>
		<!-- applicationContext.xml spring 配置檔案載入器 -->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>
	<context-param>
	 	<!--  Spring 上下文引數 --> 
	    <param-name>contextConfigLocation</param-name>  
    	<param-value>/WEB-INF/applicationContext.xml</param-value>  
	</context-param>
	<!-- 配置DispatchcerServlet -->
	<servlet>  
	    <servlet-name>demoServlet</servlet-name>  
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
	    <load-on-startup>1</load-on-startup>  
	</servlet>  
	<servlet-mapping>  
	    <servlet-name>demoServlet</servlet-name>
	    <!-- / 表示對於所有的請求的攔截,包括靜態資源如html, js, jpg等 -->
	    <url-pattern>/</url-pattern>  
	</servlet-mapping>	
	<welcome-file-list>
		<welcome-file>/index.html</welcome-file>
	</welcome-file-list>
</web-app>




2.2 demoServlet-servlet.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">


	<mvc:annotation-driven /> 
	<!-- 不攔截靜態資源 -->
	<mvc:resources location="/content/" mapping="/content/**"/>
	<!-- 配置自動掃描的包 -->
	<context:component-scan base-package="demo.mvc"></context:component-scan>
		
</beans>




2.3 applicationContext.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
       
	<!-- springmvc 檢視解析器 ,如何把handler 方法返回值解析為實際的物理檢視 -->
	<bean id="springmvcViewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 拼接物理檢視的地址字首 -->
		<property name="prefix" value="/views/"></property>
		<!-- 拼接物理檢視的地址字尾 -->
		<property name="suffix" value=".jsp"></property>
		<!-- 頁面編碼 -->
		<property name="contentType" value="text/html; charset=UTF-8"></property>
		<!-- 檢視解析器呼叫順序 order 小的先呼叫 -->
		<property name="order" value="1"/>
	</bean>
	
	<!-- 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="cache" value="false" />
		<!-- 拼接物理檢視的地址字首 -->
		<property name="prefix" value="" />
		<!-- 拼接物理檢視的地址字尾 -->
		<property name="suffix" value=".ftl" />
		<!-- 頁面編碼 -->
		<property name="contentType" value="text/html; charset=UTF-8"></property>
		<!-- 檢視解析器呼叫順序 order 小的先呼叫 -->
		<property name="order" value="0"/>
	</bean>
		
	<!-- Freemarker配置 -->
	<bean id="freemarkerConfig"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<!-- 模板載入路徑 -->
		<property name="templateLoaderPath" value="/views/"/>
        <property name="freemarkerVariables">    
            <map>    
                <entry key="xml_escape" value-ref="fmXmlEscape" />    
            </map>    
        </property> 
        <property name="defaultEncoding">    
            <value>utf-8</value>    
        </property>
		<!-- 引數設定 -->
		<property name="freemarkerSettings">
			<props>
				<prop key="template_update_delay">0</prop>
				<prop key="default_encoding">UTF-8</prop>
				<prop key="number_format">0.##########</prop>
				<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
				<prop key="classic_compatible">true</prop>
				<prop key="template_exception_handler">ignore</prop>
				<!-- 模板更新時間秒數 -->
                <prop key="template_update_delay">3600</prop>    
			</props>
		</property>
	</bean>
	<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
</beans>  




3.建立演示用的 controller , HelloController.java 

package demo.mvc.controllers;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import demo.models.hello.UserInfoModel;


/** 
*
*/
@Controller
@RequestMapping("/hello")
public class HelloController {
	/**
	 * 請求地址:專案名/hello/userinfo
	 * @return
	 */
	@RequestMapping("freemarker")
	public String freemarker(org.springframework.ui.Model model,Map<String, Object> map){
		//傳遞一個值
		model.addAttribute("val_name","張三");
		model.addAttribute("cur_time",new Date());
		
		//傳遞單個物件
		UserInfoModel info = new UserInfoModel("張三",99,"男");
		model.addAttribute("info",info);		
		
		List<UserInfoModel> list = new ArrayList<UserInfoModel>();
		list.add(new UserInfoModel("李四",20,"男"));
		list.add(new UserInfoModel("王五",21,"女"));
		list.add(new UserInfoModel("趙六",22,"男"));
		
		//傳遞多個物件
		map.put("user_list", list);
		
		return "hello/freemarker"; //servlet.xml 中定義的 字首(prefix)+返回值+字尾(suffix)拼接的實體地址
	}
}





4.建立 freemarker 模板
三個模板:
freemarker.ftl  主模板
freemarker-header.ftl 頁頭模板
freemarker-footer.ftl 頁尾模板


4.1 freemarker.ftl  主模板,內容

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
	<script scr="/content/index.js"></script>
	<link href="/content/index.css"/>
</head>
<body>
	<h3>freemarker演示</h3>
	<h4>一、傳遞一個值</h4>
	<div>姓名:${val_name}</div>
	<div>當前時間:${cur_time?string("yyyy-MM-dd HH:mm:ss zzzz")}</div>
	
	<h4>二、傳遞一個物件</h4>
	<div>name:${info.name}</div>
	<div>age:${info.age}</div>
	<div>sex:${info.sex}</div>
	<div>當前時間:${info.date?string("yyyy-MM-dd HH:mm:ss zzzz")}</div>
	
	<h4>三、傳遞一個 list 物件</h4>
	<table border="1">
		<tr>
			<td>name</td>
			<td>age</td>
			<td>sex</td>
			<td>date</td>
		</tr>
	<#list user_list as p>
		<tr>
			<td>${p.name}</td>
			<td>${p.age}</td>
			<td>${p.sex}</td>
			<td>${info.date?string("yyyy-MM-dd HH:mm:ss zzzz")}</td>
		</tr>      
    </#list>
    </table>
	<h4>四、引用其它 ftl 檔案:引用路徑是以配置檔案中(xxx.xml) templateLoaderPath 配置為基礎目錄開始的!</h4>
	<div>
		<div><#include "/hello/freemarker-header.ftl"></div>
		<div>這裡是內容</div>
		<div><#include "/hello/freemarker-footer.ftl"></div>
	</div>
    
</body>
</html>




4.2 freemarker-header.ftl 頁頭模板,內容


<h5>頁標頭檔案</h5>




4.3 freemarker-footer.ftl 頁尾模板,內容


<h5>頁尾檔案</h5>




5.請求測試,部署到 tomcat 後
訪問:http://localhost:8080/mavens-web/hello/freemarker 檢視效果

相關文章