freemarker 入门教程(servlet 容器)

第一步:在eclipse中新建javaWeb工程
第二步:添加依赖jar:freemarker-2.3.16.jar
第三步:在web.xml中添加freemarker 的servlet配置

    freemarker
    class>freemarker.ext.servlet.FreemarkerServletclass>
      
        TemplatePath  
        /  
     
      
        NoCache  
        true  
      
    
        ContentType
        text/html;charset=UTF-8
    
    
        template_update_delay
        0
    
    
        default_encoding
        UTF-8
    
      
        number_format  
        0.##########  
      
  
  
    freemarker
    *.ftl
  
  第四步:新建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 l = new ArrayList();
        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}

你可能感兴趣的:(web前端)