今天学习了FreeMarker
首先应该先下载freeMarker的jar包
http://freemarker.org/freemarkerdownload.html
或者maven项目的pom.xml导入如下依赖
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
然后,从本地jar包库里把jar包copy出来
然后,打开编辑器,新建一个web项目,把jar包粘到lib下
在webroot下新建一个文件夹 ftl ,用来存放模板,要明白freemarker的本质就是(模板+数据 = 页面)
之后在ftl里创建
basic.ftl中内内容如下
<!DOCTYPE html> <html> <head> <title>模板</title> <meta name="keywords" content="keyword1,keyword2,keyword3"> <meta name="description" content="this is my page"> <meta name="content-type" content="text/html; charset=UTF-8"> </head> <body> ${username} </body> </html>
之后
package com.sun.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public class TestServlet extends HttpServlet { //声明变量 Configuration cfg; /** * 初始化方法 */ public void init() throws ServletException { //实例化版本为2.3.23配置对象 cfg = new Configuration(Configuration.VERSION_2_3_23); //去ftl文件下加载模板文件 cfg.setServletContextForTemplateLoading(getServletContext(),"ftl"); //设置默认字符集 cfg.setDefaultEncoding("UTF-8"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获得自定义好的模板 Template tmp = cfg.getTemplate("basic.ftl"); //模拟数据 HashMap<String,String> hm = new HashMap<>(); hm.put("username", "张三"); //设置响应编码 response.setContentType("text/html;charset=UTF-8"); //获得响应输出流 PrintWriter writer = response.getWriter(); try { //将模板和数据加工,并通过响应输出流输出到页面 tmp.process(hm, writer); } catch (TemplateException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { //刷新 writer.flush(); //关闭 writer.close(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
启动tomcat通过web.xml中设置的路径访问这个servlet匹配的方法,最后
就OK了,