freemarker整合spring实例

首先导入jar包,pom文件:

<dependency>
      <groupId>org.freemarkergroupId>
      <artifactId>freemarkerartifactId>
      <version>2.3.23version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-context-supportartifactId>
      <version>4.3.14.RELEASEversion>
    dependency>

spring配置文件

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

serviceImpl:controller什么滴就不写了

@Override
    public TaotaoResult getItemHtml(Long itemId) throws IOException, TemplateException {
        //  调用服务
        TbItem tbItem = itemService.getItemByid(itemId);
        String itemDesc = itemService.getItemDescByid(itemId);
        String itemParam = itemService.getItemParamByid(itemId);
        //生成静态界面
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        //获取模板
        Template template = configuration.getTemplate("item.ftl");
        //模板数据
        Map root = new HashMap<>();
        root.put("item", tbItem);
        root.put("itemDesc", itemDesc);
        root.put("itemParam", itemParam);
        //创建writer对象,S*H读取的资源文件
        Writer out = new FileWriter(new File(STATIC_PAGE_PATH + itemId + ".html"));
        //生成静态文件
        template.process(root, out);
        out.flush();
        out.close();
        return null;
    }

模板:
复制jsp文件重命名.ftl文件
去除jsp标签,修改include标签、修改if、foreach标签

<#include "commons/header.ftl" />

……
<h1>${item.title }h1>
<strong>${item.sellPoint}strong>

 <#list item.images as pic>
                        <#if pic_index==0>
                            <li>
                                <img data-img="1" class="img-hover" alt="${item.title}" src="${pic}" width="50"
                                     height="50" data-url="${pic}">
                            li>
                        <#else>
                            <li>
                                <img data-img="1" alt="${item.title}" src="${pic}" width="50" height="50"
                                     data-url="${pic}">
                            li>
                        #if>
                    #list>

你可能感兴趣的:(-----TGB官网)