Freemarker常用指令使用示例
我的開發(fā)環(huán)境
框架:springmvc+freemarker
開發(fā)工具:springsource-tool-suite-2.9.0
JDK版本:1.6.0_29
tomcat版本:apache-tomcat-7.0.26
step1.編寫controller文件,代碼如下:
package www.asuan.com.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorldController {
@RequestMapping("/helloWorld")
public String helloWorld(Model model) {
// 示例一
int flag = 0;
model.addAttribute("flag", flag);
// 示例二
List<String> noExistList = new ArrayList<String>();
noExistList = null;
model.addAttribute("noExistList", noExistList);
// 示例三
List<String> strList = new ArrayList<String>();
strList.add("www.");
strList.add("cnblogs.");
strList.add("com/sunang");
model.addAttribute("strList", strList);
// 示例四
Map<String, String> strMap = new HashMap<String, String>();
strMap.put("mapKey0", "www.");
strMap.put("mapKey1", "cnblogs.");
strMap.put("mapKey2", "com/sunang");
model.addAttribute("strMap", strMap);
// 示例五
Date nowTime = new Date();
model.addAttribute("nowTime", nowTime);//傳輸時間對象
return "helloWorld.ftl";
}
}
step2.編寫ftl文件,代碼如下:
<html>
<body>
示例一輸出結(jié)果:
<p>
<#-- if指令的用法-->
<#-- 在指令標籤內(nèi)直接使用變量名得到文本值-->
<#if flag == 1>
flag = 1
<#elseif flag ==2>
flag = 2
<#else>
<#-- 在指令標籤外使用 ${變量名} 的格式來得到文本值-->
flag!=1 && flag!=2 flag的值為:${flag}
</#if>
</p>
<p>----------------------------------------------------------</p>
示例二輸出結(jié)果:
<p>
<#-- 判斷變量是否存在-->
<#if noExistList??>
List存在
<#else>
List不存在
</#if>
</p>
<p>----------------------------------------------------------</p>
示例三輸出結(jié)果:
<p>
<#-- list指令的用法,as可設(shè)置別名-->
<#list strList as sl>
<#-- 在變量名后加 _index 得到變量在容器中的序號,從0開始-->
<#if sl_index == 0>
我的博客地址是:${sl}
<#else>
${sl}
</#if>
</#list>
</p>
<p><p></p>
直接使用下標訪問List:${strList[0]}${strList[1]}${strList[2]}
</p>
<p>----------------------------------------------------------</p>
示例四輸出結(jié)果:
<p>
<#-- 使用 ${變量名.變量名} 獲取容器對象的子對象-->
${strMap.mapKey0}${strMap.mapKey1}${strMap.mapKey2}
</p>
<p>----------------------------------------------------------</p>
示例五輸出結(jié)果:
<p>
<#-- 當變量是日期對象時,可使用函數(shù)使其按格式輸出-->
${nowTime?string("yyyy-MM-dd")}
</p>
</body>
</html>
step3.運行與調(diào)試
將工程部署到tomcat并運行,在瀏覽器輸入:http://localhost:8080/你設(shè)置的工程名/helloWorld.htm
運行結(jié)果:
相關(guān)文章
SpringMVC使用MultipartFile 實現(xiàn)異步上傳方法介紹
這篇文章主要介紹了SpringMVC使用MultipartFile 實現(xiàn)異步上傳方法介紹,涉及pom依賴的添加,配置文件的修改等具體操作代碼,需要的朋友可以了解下。2017-09-09
Java 比較接口comparable與comparator區(qū)別解析
這篇文章主要介紹了Java 比較接口comparable與comparator區(qū)別解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-10-10
idea如何設(shè)置Git忽略對某些文件或文件夾的版本追蹤
這篇文章主要介紹了idea如何設(shè)置Git忽略對某些文件或文件夾的版本追蹤問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
springboot如何解決非controller類引用service的問題
這篇文章主要介紹了springboot如何解決非controller類引用service的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02

