FreeMarker 小试

一:在web-界面应用中:

1:加入 freemarker.jar 包到lib目录下

2:将  freemarker.ftl 放入 webapp/templates目录下

freemarker.ftl内容为:

 

<html>
 <head>
  <title>HTML模板</title>
 </head>
 <body>
  <content>
	<div>
		<font color=${color}>${words}</font>
	</div>
  </content>
 </body>
</html>
  

3:若使用 Servlet :

 

package servlet;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.Template;
 
@WebServlet("/freemarker")
public class FreeMarkerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private Configuration cfg;

	@Override
	public void init() throws ServletException {
		cfg = new Configuration();
		cfg.setServletContextForTemplateLoading(getServletContext(), "templates");
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> map = new HashMap<String, String>();
		
		map.put("color", "red");
		map.put("words", "一个简单的FreeMarker应用");
		
		Template template = cfg.getTemplate("freemarker.ftl");
		
		response.setContentType("text/html;charset=UTF-8");
		
		Writer out = response.getWriter();
		
		try {
			template.process(map, out);
		} catch (Exception e) {
			throw new ServletException("处理模板出错",e);
		}
		
	}

}

 

 

二:在简单模板应用中:

1:加入 freemarker.jar 包到lib目录下

2:将 freemarker.ftl放入 src/main/resources的 templates 目录下

3:code:

 

Configuration freemarkerConfig = new Configuration();
freemarkerConfig.setClassForTemplateLoading(SysCache.class, "/templates/");

Template template = freemarkerConfig.getTemplate(templateName);
		
template.setObjectWrapper(new DefaultObjectWrapper());
StringWriter writer = new StringWriter();
template.process(params, writer);
// 使用 emailText 发送邮件
String emailText = writer.toString(); 
 

 

 

你可能感兴趣的:(freemarker)