FreeMarker与Java框架整合

1.FreeMarker与Servlet的整合

FreeMarker与Servlet的整合有两种方式:

  • 在Servlet中直接处理模版与数据模型,然后输出到响应中。示例代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    @WebServlet(name="test",urlPatterns="/test")
    public class Test extends HttpServlet {
    private Configuration cfg;
    /**
    * @Description 初始化Configuration
    * @Author 刘俊重
    * @date 2017年11月19日
    */
    @Override
    public void init() throws ServletException {
    cfg = new Configuration(Configuration.VERSION_2_3_22);
    cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/ftl");
    }
    /**
    * @Description 接收请求
    * @Author 刘俊重
    * @date 2017年11月19日
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map map = new HashMap();
    map.put("name", "Java开发日记");
    map.put("list", Arrays.asList("张三","李四","王五"));
    Template template = cfg.getTemplate("index.ftl");
    response.setCharacterEncoding("UTF-8");
    Writer writer = response.getWriter();
    try {
    template.process(map, writer);
    } catch (TemplateException e) {
    e.printStackTrace();
    }
    }

    }

Servlet接收到test的请求之后直接在doGet方法中处理完数据与模板的整合,把处理后的数据响应给用户。

  • 配置web.xml文件:
    设置处理*.ftl的Servlet为 freemarker.ext.servlet.FreemarkerServlet。示例代码如下:
1
2
3
4
5
6
7
8
9
10
@WebServlet(name="test2",urlPatterns="/test2")
public class Test2 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("name", "Java开发日记");
request.setAttribute("list", Arrays.asList("战三","李四","王五"));
request.getRequestDispatcher("index.ftl").forward(request, response);
}

}

web.xml中进行如下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/WEB-INF/ftl</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>default_encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.ftl</url-pattern>
</servlet-mapping>
</web-app>

整段的意思是当请求test2时,将数据set进request中,并将请求转发至index.ftl页面,而又在web.xml中又进行了如下配置:所有请求以ftl结尾的文件时,都交给freemarker.ext.servlet.FreemarkerServlet处理,在这个类里面将数据和模板进行整合返回给用户。所以完整的顺序是请求先到达doGet方法,在这里面进行了请求转发至FreemarkerServlet类中完整数据和模板的组装响应给用户。

2.FreeMarker与Struts的整合

Struts框架已经好久不用了,上次用还是在大学的时候,但是Struts2默认的模版技术就是FreeMarker,所以还是有必要说一下的。Struts中使用FreeMarker非常简单,只需要在结果类型中配置result的type=”freemarker”即可。
测试类TestAction:

1
2
3
4
5
6
7
8
9
10
11
12
public class TestAction {

private String name;
private List<String> nameList;

public String execute(){
name="Java开发日记";
nameList = Arrays.asList("战三","李四","王五","赵六");
return "success";
}
//省略set/get方法
}

struts.xml的配置:

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="testfreemarker" extends="struts-default">
<action name="test" class="com.catchu.me.TestAction">
<result type="freemarker" name="success">/test.ftl</result>
</action>
</package>
</struts>

web.xml中的配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

首先在web.xml中使用过滤器配置struts的核心过滤器StrutsPrepareAndExecuteFilter,再在struts.xml中配置请求项,当请求test时交给com.catchu.me.TestAction类进行处理,如果处理结果是“success”时,响应test.ftl文件,其中结果类型是freemarker。

3.FreeMarker与SpringMvc整合

FreeMarker与SpringMvc的整合要点是配置FreeMarkerConfigurer和FreeMarkerViewResolver,即如下两个类:
bean class=”org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer”
bean class=”org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver”
TestController代码:

1
2
3
4
5
6
7
8
9
@Controller
public class TestController {
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("name", "Java开发日记");
model.addAttribute("nameList", Arrays.asList("张三","李四","王五","赵六"));
return "test";
}
}

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>withSpringMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>withSpringMvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

withSpringMvc-servlet.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<context:component-scan base-package="com.catchu.me" />

<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/" />
<property name="defaultEncoding" value="UTF-8" />
</bean>

<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="suffix" value=".ftl" />
<property name="contentType" value="text/html;charset=UTF-8" />
</bean>
</beans>

在withSpringMvc-servlet.xml中配置注解驱动,扫描包,模板路径,编码方式,后缀名等信息,当请求test时即返回一个test的model,又因为配置了后缀为ftl,即响应test.ftl文件

刘俊重 wechat
欢迎关注我的微信公众号
坚持原创技术分享