freemark小试

1. 工程结构

freemark小试


设置模板: product.ftl

<html>
	<head>
		<title>Welcome!</title>
	</head>
	<body>
		<h1>Welcome!${username}</h1>
	</body>
</html>




2. 配置: TemplateService.java

package test;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;

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

public class TemplateService {

	private static Configuration configuration = null; 
	public static String format(String ftlTemplate, Object contents) throws IOException, TemplateException, URISyntaxException{
		if(configuration == null){
			configuration = new Configuration();
		// 必须使用URI,否则setDirectoryForTemploateLoading()方法会报无法识别目录
		// 不使用URI,返回类型为URL: 
		//file:\D:\EclipseWorkSpace\work\ftl\WebRoot\WEB-INF\classes\script
		// 使用URI: 
		//D:\EclipseWorkSpace\work\ftl\WebRoot\WEB-INF\classes\script
		// getContextClassLoader().getResource("")与TemplateService.class.getResource("")区别就是一个test包路径
		// 设置模板目录
	configuration.setDirectoryForTemplateLoading(new File(new URI(Thread.currentThread().getContextClassLoader().getResource("") + "script")));
			configuration.setDefaultEncoding("UTF-8");
			
			configuration.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER);		// ★
		}
		
		// 获得freemarker模板
		Template template = configuration.getTemplate(ftlTemplate);
		
		Writer out = new StringWriter();
		
		template.process(contents, out); 
		
		out.flush();
		
		out.close();
		
		return out.toString();
	}




// 如果要在TemplateService.java中测试URL与URI,可以在Loading()之前加上一下代码

System.out.println(new File(Thread.currentThread().getContextClassLoader().getResource("") + "script"));
System.out.println(new File(Thread.currentThread().getClass().getResource("") + "script"));
System.out.println(new File(TemplateService.class.getResource("") + "script"));
System.out.println(new File(new URI(Thread.currentThread().getContextClassLoader().getResource("") + "script")));



3. 调用输出: Test01.java


package test;

import java.util.HashMap;
import java.util.Map;

public class Test01 {
	
	public static void main(String[] args) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("username", "fantasy");
		
		try {
			System.out.println(TemplateService.format("product.ftl", params));
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}




4. 输出结果

<html>
	<head>
		<title>Welcome!</title>
	</head>
	<body>
		<h1>Welcome!fantasy</h1>
	</body>
</html>



你可能感兴趣的:(java,thread,freemarker,Web,.net)