模板引擎的實質就是將頁面結構提早寫好,而後將數據渲染到模板上生成一個靜態頁面,這樣一來,下次就能夠css
直接訪問靜態文件,不用進行額外的獲取數據的操做(例如:訪問數據庫),這樣大大提高了網站的訪問速度。html
如今以一個demo爲例來學習一下Freemarker,順便提一下其中的一些細節。java
1.新建maven支持的web項目web
新建web項目,併爲其添加Maven支持,我的建議選擇MyEclipse Maven JEE Project,若是選擇下面一條的話,spring
會多出4個名字較長的文件夾,而咱們自己又不必定會用到。數據庫
2.pom.xml文件添加依賴包api
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
這裏添加了三個依賴包,spring-context-support、spring-webmvc、freemarker,記住缺一不可,缺一不可,並且,瀏覽器
所添加的兩個spring-xxx依賴包的版本最好相同,不然運行的時候可能會出現servlet初始化錯誤,這是由於這兩個包spring-mvc
相同版本之間存在依賴關係,切記!!!tomcat
3.web.xml配置
這個文件位於WebRoot--WEB-INF目錄下
<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/</url-pattern> </filter-mapping> <servlet> <servlet-name>TestFreemarker</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>TestFreemarker</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
第一個過濾器爲了防止中文亂碼而設置,第二個servlet是springmvc的。
紅字表示名稱自定義,不必定要和我寫的同樣。可是必定要和本身後面的文件名關聯起來,不要在這裏寫A,在後面
寫B,這個B天然不會指向A!!!
4.springmvc.xml配置
這裏在項目的src目錄下新建上面紅字所指的springmvc.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.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- 配置包掃描器,掃描@Controller註解的類 --> <context:component-scan base-package="eco" /> <!-- 配置註解驅動 --> <mvc:annotation-driven /> <!-- 項目視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- Freemarker配置 --> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="WEB-INF/template/" /><!-- 模板目錄 --> <property name="freemarkerSettings"> <props> <prop key="incompatible_improvements">2.3.23</prop> <prop key="template_exception_handler">rethrow</prop> <prop key="default_encoding">UTF-8</prop> <prop key="locale">UTF-8</prop><!-- 本地化設置 --> <prop key="url_escaping_charset">UTF-8</prop> </props> </property> </bean> </beans>
黃綠色字體和防止中文亂碼有關,切勿缺失!
就像你所看到的紅字那樣,WEB-INF目錄下有兩個文件夾,一個template是用來放置模板的,後綴是.ftl;
還有一個文件夾是jsp,是模板生成的jsp文件放的地方。
網上不少都添加了一個freemarker視圖解析器,說是用來訪問html,經驗證,能夠無視這個視圖解析器!!!
後面會講到。
5.創建模板文件(xxx.ftl)
按照上面所示,在WEB-INF下的view目錄下放一個模板文件(例如:01.ftl),內容以下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> This is my JSP page. <br> 姓名: ${a.name}<br> 年齡: ${a.age}<br> 性別: ${a.sex}<br> </body> </html>
這就是一個freemarker模板(jsp頁面)了,將在以後與數據相結合生成一個jsp文件,詳情請往下看。
6.SpringMVC控制器
package eco; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import freemarker.template.Configuration; import freemarker.template.Template; @Controller public class Tcontrollor { @Resource FreeMarkerConfigurer freeMarkerConfigurer; @RequestMapping("/{name}") public String Html(@PathVariable String name) { try { // 獲取鏈接 Configuration configuration = freeMarkerConfigurer .getConfiguration(); // 獲取數據 Map<String, Student> stu = new HashMap<String, Student>(); // 添加數據,這個就是本身建立的一個類 stu.put("a", new Student("桔子桑", "18", "男")); // 獲取ftl,因爲已經在配置文件中配置了路徑因此在這裏直接寫模板名稱就能夠 Template template = configuration.getTemplate("01.ftl"); // 輸出文件路徑 String dir = "D:/Tomcat 7.0/webapps/PRO/WEB-INF/jsp/" + name + ".jsp"; // Writer wr = new FileWriter(dir); OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(dir), "UTF-8"); // 寫入 template.process(stu, writer); // 關閉流 writer.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return name; } }
全是註釋,相信不難看懂。
①紅字dir是輸出文件的路徑名,後面根據此路徑名建立輸出流對象,注意的是地址要是部署到tomcat上的項目地址,
而不是你MyEclipse的workplace裏面的項目地址,由於瀏覽器只會訪問tomcat上的資源的;
②網上不少都是直接Writer wr = new FileWriter(dir),而FileWriter和FileReader是使用系統當前默認的編碼方式,
而且都不支持經過參數指定編碼方式,所以咱們須要使用FileOutputStream來爲這個輸出流對象設定UTF-8編碼,
以此來規避中文亂碼的問題。
接下來就是檢驗最終成果的時候了:
瀏覽器輸入:項目地址+66,SpringMVC的控制器結合模板和數據,到指定目錄下生成jsp文件,而且最後根據視圖
解析器訪問剛剛生成的jsp文件。
7.訪問html文件
接下來試試輸出html文件,看看能不能訪問,相關代碼做如下更改:
String dir = "D:/Tomcat 7.0/webapps/PRO/WEB-INF/jsp/" + name + ".html"; <!-- 視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".html" /> <property name="contentType" value="text/html;charset=UTF-8" /> </bean>
指定目錄下生成html文件,而且視圖解析器改成訪問該目錄下的對應html文件,來看看效果吧。
啊哦,出錯了,緣由就是,生成的WEB-INF目錄下的html文件是靜態文件,雖然控制器指示跳轉到該頁面,可是web.xml
文件中的DispatcherServlet對其進行了過濾,因此就會出現上面的狀況404(not found),咱們要作的的就是不讓
DispatcherServlet對*.html格式的文件進行過濾,方法有三:http://www.javashuo.com/article/p-cbjrjuej-dz.html
我的建議第一種(方便),在DispatcherServlet前面加上以下代碼:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
而後再來看看結果:
正如你們所願,正常跳轉到66.html,並在指定目錄生成該文件。
至此,freemarker模板引擎的使用告一段落,至於模板的一些語法,往後再做探討。睡覺~~~~·