模板框架freemarker使用

本文详细介绍如何在Spring MVC项目中集成Freemarker模板引擎,包括必要的配置步骤、示例代码及视图展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

apache freemarker is a temlpate engine:

output = Template + data - model

直接上干货,有兴趣可以直接引用。。。

example:

1.build a spring hibernate springMVC project; add freemarker.jar too buildpath...

2.相关配置文件如下, 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    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_2_5.xsd">
    
    <!-- Spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath*:spring-main.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 使用Filter解决中文乱码问题 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- SpringMVC前端控制器 -->
    <servlet>
        <servlet-name>springmvc_alspd</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>
                contextConfigLocation
            </param-name>
            <param-value>
                classpath*:spring-mvc.xml
            </param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc_alspd</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <!-- 解决:Could not obtain transaction-synchronized Session for current thread -->
    <filter>
        <filter-name>SpringOpenSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SpringOpenSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

 

spring-main.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-4.0.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
     http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd"
    default-autowire="byName" default-lazy-init="true">

    <!-- 引入properties文件 -->
    <!-- <context:property-placeholder location="classpath*:config/jdbc.properties"
        /> -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>classpath:jdbc.properties</value>
            <!-- <value></WEB-INF/jdbc.properties</value> -->
        </property>
    </bean>
    <!-- 定义数据库连接池数据源bean destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <!-- 设置JDBC驱动名称 -->
        <property name="driverClass" value="${jdbc.driver}" />
        <!-- 设置JDBC连接URL -->
        <property name="jdbcUrl" value="${jdbc.url}" />
        <!-- 设置数据库用户名 -->
        <property name="user" value="${jdbc.username}" />
        <!-- 设置数据库密码 -->
        <property name="password" value="${jdbc.password}" />
        <!-- 设置连接池初始值 -->
        <property name="initialPoolSize" value="5" />
    </bean>
    <!-- 配置sessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource" />

        <!-- hibernate的相关属性配置 -->
        <property name="hibernateProperties">
            <value>
                <!-- 设置数据库方言 -->
                hibernate.dialect=org.hibernate.dialect.MySQLDialect
                <!-- 设置自动创建|更新|验证数据库表结构 -->
                hibernate.hbm2ddl.auto=update
                <!-- 是否在控制台显示sql -->
                hibernate.show_sql=false
                <!-- 是否格式化sql,优化显示 -->
                hibernate.format_sql=true
                <!-- 是否开启二级缓存 -->
                hibernate.cache.use_second_level_cache=false
                <!-- 是否开启查询缓存 -->
                hibernate.cache.use_query_cache=false
                <!-- 数据库批量查询最大数 -->
                hibernate.jdbc.fetch_size=50
                <!-- 数据库批量更新、添加、删除操作最大数 -->
                hibernate.jdbc.batch_size=50
                <!-- 是否自动提交事务 -->
                hibernate.connection.autocommit=true
                <!-- 指定hibernate在何时释放JDBC连接 -->
                hibernate.connection.release_mode=auto
                <!-- 创建session方式 hibernate4.x 的方式 -->
                hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
                <!-- javax.persistence.validation.mode默认情况下是auto的,就是说如果不设置的话它是会自动去你的classpath下面找一个bean-validation**包
                    所以把它设置为none即可 -->
                javax.persistence.validation.mode=none
            </value>
        </property>
        <!-- 自动扫描实体对象 -->
        <property name="packagesToScan" value="com.alspd.job.entity" />
    </bean>
    <!-- 定义事务管理 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="merge*" propagation="REQUIRED" />
            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="put*" propagation="REQUIRED" />
            <tx:method name="execute*" propagation="REQUIRED"
                rollback-for="Exception.class" />
            <tx:method name="tes*" propagation="REQUIRED" />
            <tx:method name="use*" propagation="REQUIRED" />
            <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 -->
            <tx:method name="get*" propagation="REQUIRED" read-only="true" />
            <tx:method name="count*" propagation="REQUIRED" read-only="true" />
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />
            <tx:method name="list*" propagation="REQUIRED" read-only="true" />
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception.class" />
        </tx:attributes>
    </tx:advice>
    <bean id="transactionProxy"
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
        abstract="true" lazy-init="true">
        <property name="transactionManager" ref="transactionManager"></property>
        <property name="transactionAttributes">
            <props>
                <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="tes*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="execute*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="query*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>
                <prop key="load*">PROPAGATION_REQUIRED, -Exception</prop>
            </props>
        </property>
    </bean>

    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.alspd.job">
        <context:exclude-filter expression="org.springframework.stereotype.Controller"
            type="annotation" />
    </context:component-scan>
    <!-- 配置声明式事务:方法一,在Service实现类或者public实现方法上使用注解@Transactional,则此类或方法就会启用事务机制 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    <!-- 下面三个Bean的配置可有可无,但配置后用处更大,通常用于BaseDao类、其他Dao类或特殊工具类中 -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"
        p:sessionFactory-ref="sessionFactory" />

    <bean id="hibernateDaoSupport"
        class="org.springframework.orm.hibernate4.support.HibernateDaoSupport"
        p:hibernateTemplate-ref="hibernateTemplate" abstract="true" />

    <bean id="sessionFactoryUtils" class="org.springframework.orm.hibernate4.SessionFactoryUtils"
        abstract="true" />


    <!-- Freemarker配置 -->
    <bean id="freemarkerConfig"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/templates/" />
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">0</prop>
                <prop key="default_encoding">UTF-8</prop>
                <prop key="number_format">0.##########</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="classic_compatible">true</prop>
                <prop key="template_exception_handler">ignore</prop>
            </props>
        </property>
    </bean>
</beans>

 

springMVC.xml

<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.alspd.job"
        use-default-filters="false">
        <context:include-filter expression="org.springframework.stereotype.Controller"
            type="annotation" />
    </context:component-scan>

    <!-- 开启RequestMapping注解 -->
    <mvc:annotation-driven />

    <!-- TODO mvc:resource -->

    <!-- 处理请求转发 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576000" />
    </bean>

    <!-- 在处理器实现Controller时,需要配置bean -->
    <!-- <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> -->
    <bean name="/hello" class="com.alspd.job.controller.HelloController" />

    <!-- 自定义HandlerInterceptor配置 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/test/**" />
            <bean class="com.alspd.job.common.MyInterceptor"></bean>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/test/**" />
            <bean class="com.alspd.job.common.MyInterceptor2"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

    <!--视图解释器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="order" value="1"></property>
        <property name="suffix">
            <value>.ftl</value>
        </property>
        <property name="contentType" value="text/html;charset=UTF-8"></property>
    </bean>

</beans>

来一个Controller:

@RequestMapping("freemarker")
    public String freemarker(HttpServletRequest req, HttpServletResponse resp) {
        Configuration configuration = new Configuration();
        configuration.setServletContextForTemplateLoading(req.getSession()
                .getServletContext(), "/WEB-INF/templates");
        List<TUser> userList = service.getUserList();
        Map<String,Object> root = new HashMap<>();
        root.put("list", userList);
        
        Template template;
        Writer out;
        try {
            template = configuration.getTemplate("test.ftl");
            out = resp.getWriter();
            template.process(root, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "user";
    }

 

记得***.tfl文件啊

example:

<html>
    <head>
        <title>freeMarker test</title>
    </head>
    <body>
        <#list list as user>
         userId:${user.id}
         &nbsp;&nbsp;&nbsp;
         userName:${user.name}
         &nbsp;&nbsp;&nbsp;
         userPassword:${user.password}
         &nbsp;&nbsp;&nbsp;
         userPhone:${user.phone}
         <br/>
         <hr/>
        </#list>
        <hr/>
        
    </body>
</html>

 

orver。。。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值