初始Freemarker

本文介绍了Freemarker,一个强大的Java模板引擎。讲解了它的概念、特点,通过例子展示了模板的组成部分,包括文本、注释、插值和FTL指令。还提供了在Java项目中使用Freemarker的基本步骤,包括导入jar包、编写模板、创建实体类和测试类。最后,解释了Freemarker的运行原理和一句话总结。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、什么是freemarker?

1、概念:FreeMarker 是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java等

2、特点:通用性高,模板语言强大;模板编写为FreeMarkerTemplateLanguage(FTL)

3、模板组成部分:

a)  文本:直接输出的部分

b) 注释:<#-- ... -->格式部分,不会输出

c) 插值:即${...}或#{...}格式的部分,将使用数据模型中的部分替代输出

d) FTL指令:FreeMarker指定,和HTML标记类似,名字前加#予以区分,不会输出

举例说明:

<html><br>
<head><br>
<title>Welcome!</title><br>
</head><br>
<body><br>
<#-- 注释部分 --><br>
<#-- 下面使用插值 -->
<h1>Welcome ${user} !</h1><br>
<p>We have these animals<br>
<u1><br>
<#-- 使用FTL指令 -->
<#list animals as being><br>
   <li>${being.name} for ${being.price} Euros<br>
<#list><br>
<u1><br>
</body><br>
</html>

二、做个java项目进行举例

1、导入jar包:freemarker.jar

2、写一个模板(举例):

Freemarker的版本号:${.version}

编号:${userId}

名字:${userName}

年龄:${userAge}

3、导入freemarkerUtil:

package com.lxp.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * FreeMarker模板工具类
 * @author:李鑫鹏
 * @时间:2018年3月29日 上午10:57:43
 */
public class FreemarkerUtil {

    /**
     * @param templatePath 模块文件的路径
     * @param templateName 模板文件名称
     * @param map 数据模型根对象
     * @param templateEncoding 模板文件的编码方式
     */
    public static String getTemplate(String templatePath, String templateName, String templateEncoding, Map<String,Object> map){
      
        Writer writer = null;
        try {
            Configuration config=new Configuration();
            File file=new File(templatePath);
           
            //设置要解析的模板所在的目录,并加载模板文件
            config.setDirectoryForTemplateLoading(file);

            //获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致
            Template template=config.getTemplate(templateName,templateEncoding);
            
            //合并数据模型与模板
            writer = new StringWriter();
            template.process(map, writer);
            
            return writer.toString();
        
        } catch (Exception e) {
            e.printStackTrace();
        }finally
        {

            //关流
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}

4、写个实体类

package com.lxp.bean;

/**  
 * @Description: 用户实体类
 * @author: 李鑫鹏 
 * @date 2018年4月19日  
 */  
public class UserInfo {

	//用户编号
	private int userId;
	
	//用户名称
	private String userName;
	
	//用户年龄
	private Integer userAge;
	
	//get()、set()方法
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public Integer getUserAge() {
		return userAge;
	}
	public void setUserAge(Integer userAge) {
		this.userAge = userAge;
	}
	
	//有参构造
	public UserInfo(int userId, String userName, Integer userAge) {
		super();
		this.userId = userId;
		this.userName = userName;
		this.userAge = userAge;
	}
	
	//无参构造
	public UserInfo() {
		super();
	}
	
	//toString()方法
	@Override
	public String toString() {
		return "UserInfo [userId=" + userId + ", userName=" + userName
				+ ", userAge=" + userAge + "]";
	}
}

5、写个测试类:

package com.lxp.test;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import com.lxp.util.FreemarkerUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @Description: 测试类
 * @author:李鑫鹏
 * @date:2018年3月23日
 */
public class TestDemo {
	
	/**         
         * @Description:使用FreeMarker工具类
	 * @date 2018年3月29日 上午10:56:30
	 * @author 李鑫鹏
	 */
	@Test
	public void testDemo2(){
            
                //创建map对象
		Map<String, Object> mapUser = new HashMap<String, Object>();
		
		mapUser.put("userid", 101);
		mapUser.put("username", "张三");
		mapUser.put("userage", 25);
		
		String string = FreemarkerUtil.getTemplate("ftl/", "test.ftl", "GBK",mapUser);
		System.out.println(string);
	}
}
6、运行结果:
Freemarker的版本号:2.3.20

编号:101

名字:张三

年龄:25

三、如果不想用FreemarkerUtil工具类可以一步一步进行测试:

1、与以上的1、2、4 步相同

2、写个测试类:

package com.lxp.test;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import com.lxp.util.FreemarkerUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @Description: 测试类
 * @author:李鑫鹏
 * @date:2018年3月23日
 */
public class TestDemo {
	
	/**   
	 * @Description: 没有用FreemarkerUtil工具类
	 * @return void    返回类型  
	 * @author 李鑫鹏
	 * @date 2018年4月19日
	 * @throws  
	 */  
	@Test
	public void testDemo1(){
		
		/**
		 * 方法二:
		 * 1、获取配置:configuration
		 * 2、获取读取模板路径
		 * 3、获取模板
		 * 4、添加数据
		 * 5、模板生成
		 */
		//1、获取配置:configuration
		Configuration config = new Configuration();
		try {
			
			//2、获取读取模板路径
			config.setDirectoryForTemplateLoading(new File("ftl/"));
			
			//3、获取模板
			Template template = config.getTemplate("test.ftl");
			
			//4、添加数据
			Writer writer = new StringWriter();
			
			Map<Object,Object> map = new HashMap<Object, Object>();
			map.put("userId", 101);
			map.put("userName", "李鑫鹏");
			map.put("userAge", 24);
			
			//5、模板生成
			template.process(map,writer);
			
			System.out.println(writer);
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}		
}

3、运行结果:

Freemarker的版本号:2.3.20

编号:102

名字:李鑫鹏

年龄:24

四、运行原理

   将需要的页面样式放入freemarker模板中,然后将其动态绑定,并放入map中,调用模板页面将其生成静态页面


五、一句话进行总结

         数据模板 + 模板 = 输出











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值