FreeMarker与Spring集成

本章节介绍怎样将 FreeMarker 和传统的 Spring MVC 进行集成。具体集成步骤如下:

(1)先看看 Spring MVC 项目的整体结构,其中包含了一个控制器Controller、一个xml配置文件、一个FreeMarker模版和web.xml文件。这是一个传统的web项目,打包方式为 war。如下图:

(2)在 resources 目录下面创建 applicationContent.xml 文件,该文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="https://www.springframework.org/schema/context"
    xsi:schemaLocation="https://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        https://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context-3.0.xsd"
    default-lazy-init="false">

    <!-- 扫描路径 -->
    <context:component-scan base-package="com.hxstrive"/>
    <context:annotation-config />

    <!-- annotation默认的方法映射适配器 -->
    <!--<bean id="handlerMapping"-->
          <!--class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>-->
    <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
        <!--<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>-->
    <!--</bean>-->

    <!--3:配置JSP 显示ViewResolver-->
    <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
        <!--<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>-->
        <!--<property name="prefix" value="/"/>-->
        <!--<property name="suffix" value=".jsp"/>-->
    <!--</bean>-->

    <!-- 配置freeMarker的模板路径  -->
    <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
    <bean id="freemarkerConfig"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/views" />
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">1</prop>
                <prop key="defaultEncoding">UTF-8</prop>
                <prop key="url_escaping_charset">UTF-8</prop>
                <prop key="locale">zh_CN</prop>
                <prop key="boolean_format">true,false</prop>
                <prop key="date_format">yyyy-MM-dd</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="time_format">HH:mm:ss</prop>
                <prop key="number_format">0.######</prop>
                <prop key="whitespace_stripping">true</prop>
            </props>
        </property>
        <property name="freemarkerVariables">
            <map>
                <entry key="xml_escape" value-ref="fmXmlEscape" />
            </map>
        </property>
    </bean>

    <!-- 配置freeMarker视图解析器 -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
        <property name="viewNames" value="*.ftl"/>
        <property name="contentType" value="text/html; charset=utf-8"/>
        <property name="prefix" value=""/>
        <property name="suffix" value=""/>
        <property name="order" value="2"/>
        <property name="cache" value="false"/>
    </bean>

</beans>

(3)创建 com.hxstrive.HomeController 控制器,控制器完整代码如下:

package com.hxstrive;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Controller
public class HomeController {

    @RequestMapping("/")
    public String home(Map<String,Object> map) {
        map.put("title", "Spring 集成 FreeMarker");
        map.put("date", new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss").format(new Date()));
        return "index.ftl";
    }

}

(4)在 webapp 目录下面创建 views 目录,然后在 views 目录中创建 index.ftl FreeMarker 模版文件。模版文件内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Spring 集成 FreeMarker</title>
</head>
<body>

<h1>${title?default('title')}</h1>
<p>${date?default('')}</p>

</body>
</html>

(5)在 web.xml 文件中配置 Spring 过滤器,加载配置文件等。如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="https://java.sun.com/xml/ns/javaee"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
        https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- 装载配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- 启动时由spring监听 -->
    <listener>
        <!-- 用于从 RequestContextHolder 中获取Request对象 -->
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Spring MVC核心控制器 -->
    <servlet>
        <servlet-name>controller</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>controller</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

    <!-- 配置session过期时间 -->
    <!-- filter、listener、servlet、servlet-mapping等元素要在session-config之前 -->
    <session-config>
        <session-timeout>-1</session-timeout>
    </session-config>

</web-app>

(6)给项目添加 Spring 和依赖库的 Maven 依赖。pom.xml 文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0"
         xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://maven.apache.org/POM/4.0.0
            https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>freemarker_learn</artifactId>
        <groupId>com.hxstrive</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>demo3</artifactId>
    <packaging>war</packaging>

    <properties>
        <spring.version>4.3.20.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- FreeMarker 依赖 -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

</project>

(7)使用tomcat运行项目,启动成功后在浏览器访问,如下图(其中 demo3为项目名):

实例完整代码见 demo3 子模块。

说说我的看法
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
公众号