FreeMarker与Servlet结合示例

一、最原始示例

1、引入POM依赖

        <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.26-incubating</version>
        </dependency>

        <!-- Servlet Library -->
        <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

2、在WEB-INF/ftl中建立test.ftl

<html>
<head>
  <title>Welcome!</title>
</head>
<body>
  <h1>
    Welcome ${user}<#if user == "Big Joe">, our beloved leader</#if>!
  </h1>
</body>
</html>

3、添加TestServlet.java

package com.jsoft.testfreemarker;

import java.io.IOException;
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;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet(name = "test", urlPatterns = "/test")
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private Configuration cfg;

    @Override
    public void init() throws ServletException {
        // initialize operation
        cfg = new Configuration(Configuration.VERSION_2_3_26);
        cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/ftl");
    }

    /**
     * Default constructor.
     */
    public TestServlet() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("user", "Big Joe");
        // 得到模板
        try {
            // 将模板和数据结合,并返回浏览器
            Template template = cfg.getTemplate("test.ftl");
            template.process(data, response.getWriter());
        } catch (Exception e) {
            // e.printStackTrace();
            response.getWriter().print("暂时无数据");
        }
    }

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

}

提示:采用了Servlet3.x的注解功能,不需要在web.xml中再配置映射。

4、测试效果

 

测试工程:https://github.com/easonjim/5_java_example/tree/master/freemarker/test2

 

二、高级一点的集成

1、在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>

2、新建test.ftl模板文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr">  
<head>  
 <title>test!</title>  
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
</head>  
<body>  
    <div>  
        直接显示字符串<br />  
        String:${strValue}<br/>     
        <hr/>  
    </div>  
      
    <div>  
    显示日期  
    date:${myDate?date}<br/>  
    <hr/>  
    显示时间  
    time:${myDate?time}<br/>  
    <hr/>  
    显示时间戳  
    datetime:${myDate?datetime}<br/>  
    <hr/>   
    </div>  
      
    <div>  
    访问对象数组  
    ObjectArray:  
    ${objectArray[0]},${objectArray[1]},${objectArray[2]}  
    <br />  
    <hr/>       
    </div>  
      
    <div>  
    遍历Set中的元素  
    SetData:<br />  
    <#list setData as value>  
        ${value}  
    </#list>  
    <hr/>   
    </div>  
      
    <div>  
    遍历List中的元素  
    strList:<br/>  
    <#list strList as strValue >  
    <#if strValue_index == 0>  
        ${strValue} is first element  
    <#elseif !strValue_has_next>  
        ${strValue} is last element  
    <#else>  
        ${strValue}  
    </#if>  
    <br />  
    </#list>  
    <hr/>   
    </div>  
      
    <div>  
    获取map中的值  
    <br/>  
    map:  
    key1=${map.key1},key2=${map.key2},key3=${map.key3}  
    <hr/>       
    </div>  
      
      
    <#include "foot.html">  
</body>     
</html>    

foot.html为了演示模板中引入文件的效果

<div style="margin-top: 50px;text-align: center;font-size: 12px">  
<hr />  
this is foot  
</div>  

3、编写Servlet,这次的Servlet完全不用涉及到FreeMarker的类库使用,只关心Model即可。

package com.jsoft.testfreemarker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

/**
 * Servlet implementation class TestServlet
 */
@WebServlet(name = "test", urlPatterns = "/test")
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public TestServlet() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String strValue = "this is String";
        Date myDate = new Date();
        Object[] objectArray = new Object[] { 1, "str", 1.2 };

        Set<Object> setData = new HashSet<Object>();
        setData.add("dataValue1");
        setData.add("dataValue2");
        setData.add("dataValue3");

        List<String> strList = new ArrayList<String>();
        strList.add("字符串1");
        strList.add("字符串2");
        strList.add("字符串3");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");

        request.setAttribute("strValue", strValue);
        request.setAttribute("objectArray", objectArray);
        request.setAttribute("strList", strList);
        request.setAttribute("map", map);
        request.setAttribute("myDate", myDate);
        request.setAttribute("setData", setData);
        request.getRequestDispatcher("/WEB-INF/ftl/test.ftl").forward(request, response);
    }

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

}

4、测试效果

 

测试工程:https://github.com/easonjim/5_java_example/tree/master/freemarker/test3

posted @ 2017-06-28 18:17  EasonJim  阅读(3360)  评论(0编辑  收藏  举报