欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Freemarker常用指令使用示例

程序员文章站 2024-02-12 16:28:04
我的开发环境框架:springmvc+freemarker开发工具:springsource-tool-suite-2.9.0jdk版本:1.6.0_29tomcat版本:...

我的开发环境
框架:springmvc+freemarker
开发工具: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>
示例一输出结果:
<p>
<#-- if指令的用法-->
<#-- 在指令标籤内直接使用变量名得到文本值-->
<#if flag == 1>
    flag = 1
<#elseif flag ==2>
    flag = 2
<#else>
    <#-- 在指令标籤外使用   ${变量名}   的格式来得到文本值-->
    flag!=1 && flag!=2 flag的值為:${flag}
</#if>
</p>
<p>----------------------------------------------------------</p>
示例二输出结果:
<p>
<#-- 判断变量是否存在-->
<#if noexistlist??>
    list存在
<#else>
    list不存在
</#if>
</p>
<p>----------------------------------------------------------</p>
示例三输出结果:
<p>
<#-- list指令的用法,as可设置别名-->
<#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>
示例四输出结果:
<p>
<#-- 使用    ${变量名.变量名}   获取容器对象的子对象-->
${strmap.mapkey0}${strmap.mapkey1}${strmap.mapkey2}
</p>
<p>----------------------------------------------------------</p>
示例五输出结果:
<p>
<#-- 当变量是日期对象时,可使用函数使其按格式输出-->
${nowtime?string("yyyy-mm-dd")}
</p>
</body>
</html>

step3.运行与调试

将工程部署到tomcat并运行,在瀏览器输入:你设置的工程名/helloworld.htm
运行结果:

Freemarker常用指令使用示例