美文网首页
Freemarker_笔记

Freemarker_笔记

作者: bboymonk | 来源:发表于2017-03-24 12:28 被阅读0次

Spring集成Freemarker:

applicationContext.xml
<bean id="freemarkerConfig"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="classpath:view/" />
        <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>

spring-servlet.xml

<!--注入扫描-->
    <context:component-scan base-package="com.zj.controller" />

    <!-- 启动Spring MVC的注解功能 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

    <!-- 针对freemarker的视图配置 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="cache" value="true" />
        <property name="prefix" value="" />
        <property name="suffix" value=".ftl" />
        <property name="contentType" value="text/html;charset=UTF-8"></property>
        <property name="requestContextAttribute" value="request" />
        <property name="exposeSpringMacroHelpers" value="true" />
        <property name="exposeRequestAttributes" value="true" />
        <property name="exposeSessionAttributes" value="true" />
    </bean>

web.xml

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/config/spring/spring.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/config/spring/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

基本用法:

${user}

<#--=============if==================-->
<#if random gt 60>
    成绩合格
<#elseif random gte 85>
    成绩优秀
<#else>
    不合格
</#if>

<#--===================include==================-->
<#include "abc.txt">
<#--====================遍历List===================-->
<#list userList as user>
${user_index+1}
    用户名;${user.userName}
    phone;${user.phone}
    地址:${user.address}
<#--如果对时间进行格式化可以用:${user.date?string('yyyy-MM-dd')}-->
<#--====================共有几个用户=====================-->
<#if !user_has_next>
    共有${userList?size}个用户
</#if>
</#list>

<#--============================排序测试=======================-->
<#list userList?sort_by("phone") as user>
用户名;${user.userName}
phone;${user.phone}
地址:${user.address}
<#if (user.userName == "taisuke")>
    <#break>
</#if>
</#list>
<#--=========================宏指令=================-->
<#macro method a b c>
    ${a}===${b}====${c}
</#macro>
<@method "wjb" "wjb2" "wjb3"></@method>
<#--======================定义一个变量==================-->
<#assign email="163@qq.com">
${email}

SpringBoot配置Freemarer:

server:
  port: 8080
  session:
    timeout: 300000
 #============================freemarker配置=========================#
spring:
  freemarker:
    suffix: .html
    template-loader-path: classpath:/templates/html/
    charset: UTF-8
    cache: false
    expose-request-attributes: true
    request-context-attribute: request
    content-type: text/html

编写FreemarkerConfig类:

package com.pd.gch.commpents;

import com.pd.gch.utils.ViewFreeMarker;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;


@Component
public class FreeMarkerConfig {
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Bean
    public Configuration getFreeMarkerConfiguration(){
        return freeMarkerConfigurer.getConfiguration();
    }

    public void resolveMap(Map<String,String> model, String templateName){
        try {
            Template template = this.getFreeMarkerConfiguration().getTemplate(templateName);
            template.setDateFormat("yyyy-MM-dd HH:mm:ss");
            template.setDateFormat("yyyy-MM-dd");
            template.setTimeFormat("HH:mm:ss");
            template.process(model, new OutputStreamWriter(System.out));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    @Bean
    public FreeMarkerViewResolver freeMarkerViewResolver(){
            FreeMarkerViewResolver freeMarkerViewResolver= new FreeMarkerViewResolver();
        freeMarkerViewResolver.setContentType("text/html;charset=UTF-8");
        freeMarkerViewResolver.setViewClass(new ViewFreeMarker().getClass());
        return freeMarkerViewResolver;
    }
}

配置全局path变量

public class ViewFreeMarker extends FreeMarkerView {
    private static final String CONTEXT_PATH = "base";

    @Override
    protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
        model.put(CONTEXT_PATH, request.getContextPath());
        super.exposeHelpers(model, request);
    }
}

相关文章

网友评论

      本文标题:Freemarker_笔记

      本文链接:https://www.haomeiwen.com/subject/gooxottx.html