當前位置:才華齋>計算機>java語言>

關於java Spring整合Freemarker的詳細步驟

java語言 閱讀(2.93W)

我的開發環境

關於java Spring整合Freemarker的詳細步驟

框架:springmvc

開發工具:springsource-tool-suite-2.9.0

版本:1.6.0_29

tomcat版本:apache-tomcat-7.0.26

前言:FreeMarker是一個用Java語言編寫的模板引擎,它基於模板來生成文字輸出。FreeMarker與Web容器無關,即在Web執行時,它並不知道Servlet或HTTP。它不僅可以用作表現層的實現技術,而且還可以用於生成XML,JSP或Java 等。

簡而言之,Freemarker就是在Jave Web開發中以模板的方式在頁面展示從服務端獲取的資訊。

step1.引入jar包

Maven程式碼:

複製程式碼 程式碼如下:

marker

freemarker

2.3.20

ngframework

spring-context-support

ASE

step2.在src/main/resources/conf目錄下新建Freemarker屬性檔案erties,此屬性檔案定義了Freemarker常用的.編碼轉換,程式碼如下:

tag_syntax=auto_detect

template_update_delay=2

default_encoding=UTF-8

output_encoding=UTF-8

locale=zh_CN

date_format=yyyy-MM-dd

time_format=HH:mm:ss

datetime_format=yyyy-MM-dd HH:mm:ss

step3.在DispatcherServlet上下文配置檔案中新增Freemarker所需的配置,程式碼如下:

複製程式碼 程式碼如下:

*

step4.編寫controller檔案和ftl檔案

在src/main/java目錄下新建包roller,在包下新建,程式碼如下:

複製程式碼 程式碼如下:

package roller;

import roller;

import l;

import estMapping;

@Controller

public class HelloWorldController {

@RequestMapping("/helloWorld")

public String helloWorld(Model model) {

String word0 = "Hello ";

String word1 = "World!";

//將資料新增到檢視資料容器中

ttribute("word0",word0);

ttribute("word1",word1);

return "";

}

}

在step3中配置的WEB-INF/ftl路徑下新建,程式碼如下:

複製程式碼 程式碼如下:

${word0}${word1}

step5.執行與除錯

工程部署到tomcat並執行,在瀏覽器中訪問:http://localhost:8080/你設定的工程名/

執行結果: