第一步:在eclipse中新建javaWeb工程
第二步:添加依赖jar:freemarker-2.3.16.jar
第三步:在web.xml中添加freemarker 的servlet配置
<servlet>
    <servlet-name>freemarker</servlet-name>
    <servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
    <init-param>  
        <param-name>TemplatePath</param-name>  
        <param-value>/</param-value>  
    </init-param> 
    <init-param>  
        <param-name>NoCache</param-name>  
        <param-value>true</param-value>  
    </init-param>  
    <init-param>
        <param-name>ContentType</param-name>
        <param-value>text/html;charset=UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>template_update_delay</param-name>
        <param-value>0</param-value>
    </init-param>
    <init-param>
        <param-name>default_encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>  
        <param-name>number_format</param-name>  
        <param-value>0.##########</param-value>  
    </init-param>  
  </servlet>
  <servlet-mapping>
    <servlet-name>freemarker</servlet-name>
    <url-pattern>*.ftl</url-pattern>
  </servlet-mapping>
  第四步:新建servlet,并编写测试代码:
  package cn.zhangheng.filter;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        List<String> l = new ArrayList<String>();
        l.add("hello");
        l.add("freemarker");
        request.setAttribute("list", l);
        try {
            request.getRequestDispatcher("/demo.ftl").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
第五步:在index.ftl中循环数据
<#list list as l>
${l}
</#list>
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐