【freemarker】简单使用

freemarker简单使用

  • 依赖
<!-- feermarker -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.28</version>
</dependency>
  • 创建对象
@Data
@ToString
public class Student {
    private String name;//姓名
    private int age;//年龄
    @JsonProperty("dd.MM.yyyy HH:mm:ss")
    private Date birthday;//生日
    private Float money;//钱包
    private List<Student> friends;//朋友列表
    private Student bestFriend;//最好的朋友

}
  • 创建模板【ftl1.ftl】
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf‐8">
    <title>Hello World!</title>
</head>
<body>
    <h1>Hello ${name}!</h1>
    <h2>1-对象</h2>
    <#--
        // 1-放置对象
        Student stu1 = new Student();
        stu1.setName("xiaoai");
        stu1.setAge(21);
        stu1.setMoney(1000.86f);
        stu1.setBirthday(new Date());
        map.put("stu1",stu1);//向数据模型放数据
    -->
    -----stu1-----<br/>
    name:${stu1.name}<br/>
    age:${stu1.age}<br/>
    money:${stu1.money}<br/>
    birthday:${stu1.birthday?string("yyyy年MM月dd日 HH:mm:ss")}<br/>



    <h2>2-列表遍历  + if判断</h2>
    <#--
    -->
    <table border="1px solid">
        <tr>
            <td>姓名</td>
            <td>年龄</td>
            <td>出生日期</td>
            <td>钱包</td>
            <td>最好的朋友</td>
            <td>朋友个数</td>
            <td>朋友列表</td>
        </tr>
        <#if stuList??> <#--如果stuList存在-->
            <#list stuList as stu>
                <tr>
                    <td
                       <#if stu.name =='xiaoai'>
                            style="background:red;"
                       </#if>
                    >
                        ${stu.name!''}
                    </td>
                    <td>${stu.age}</td>
                    <td>${(stu.birthday?date)!''}</td>
                    <td>${stu.money}</td>
                    <td>${(stu.bestFriend.name)!''}</td>
                    <td>${(stu.friends?size)!0}</td>
                    <td>
                        <#if stu.friends??>
                            <#list stu.friends as firend>
                                ${firend.name!''}<br/>
                            </#list>
                        </#if>
                    </td>
                </tr>
            </#list>
        </#if>
    </table>

    <h2>3-list</h2>
    <#--

    -->
    <table border="1px solid">
        <tr>
            <td>序号</td>
            <td>姓名</td>
            <td>年龄</td>
            <td>钱包</td>
        </tr>
        <#list stuList as stu>
            <tr>
                <td>${stu_index + 1}</td>
                <td>${stu.name}</td>
                <td>${stu.age}</td>
                <td>${stu.money}</td>
            </tr>
        </#list>
    </table>

    <h2>4-map</h2>
    <#--
    -->
    输出学生信息:<br/>
    -----stu1-----<br/>
    name:${stuMap['stu1'].name}<br/>
    age:${stuMap['stu1'].age}<br/>
    -----stu2-----<br/>
    name:${stuMap.stu2.name}<br/>
    age:${stuMap.stu2.age}<br/>

    遍历学生:<br/>
    <table border="1px solid">
        <tr>
            <td>序号</td>
            <td>姓名</td>
            <td>年龄</td>
            <td>钱包</td>
        </tr>
        <#list stuMap?keys as key>
            <tr>
                <td>${key_index +1 }</td>
                <td>${stuMap[key].name}</td>
                <td>${stuMap[key].age}</td>
                <td>${stuMap[key].money}</td>
            </tr>
        </#list>
    </table>

    <h2>指令1:if</h2>
    <#--

    -->
    <h2>内建函数:</h2>
    1-集合大小:${stuList?size}<br>
<#--    2-函数引用:${stu1?toString}-->

    <p>end...</p>
</body>
</html>
  • 添加接口
@RequestMapping("/freemarker")
@Controller
public class FreemarkerController {

//    @Autowired
//    RestTemplate restTemplate;


    @RequestMapping("/ftl1")
    public String freemarker(Map<String, Object> map){
        map.put("name","xiaoai");

        // 1-放置对象
        Student stu1 = new Student();
        stu1.setName("xiaoai");
        stu1.setAge(21);
        stu1.setMoney(1000.86f);
        stu1.setBirthday(new Date());
        map.put("stu1",stu1);//向数据模型放数据

        // 2-列表
        Student stu2 = new Student();
        stu2.setName("xiaoai2");
        stu2.setAge(25);
        stu2.setMoney(4000.86f);
        stu2.setBirthday(new Date());
        // 朋友列表
        Student stu3 = new Student();
        stu3.setName("xiaoai3");
        stu3.setAge(23);
        stu3.setMoney(43300.86f);
        stu3.setBirthday(new Date());
        List<Student> friends = new ArrayList<>();
        friends.add(stu1);
        friends.add(stu3);
        stu2.setFriends(friends);
        stu2.setBestFriend(stu1);

        // 3-list
        List<Student> stuList = new ArrayList<>();
        stuList.add(stu1);
        stuList.add(stu2);
        map.put("stuList",stuList); //向数据模型放数据

        //map
        HashMap<String,Student> stuMap = new HashMap<>();
        stuMap.put("stu1",stu1);
        stuMap.put("stu2",stu2);
        map.put("stuMap",stuMap);//向数据模型放数据

        //返回模板文件名称
        return "ftl1";
    }
}

静态化

一、简单模板静态化

  • 创建模板【test.ftl】
{
    "cityId": ${cityId},
    "cityName": ${cityName},
    "cky2":  ${cky2},
    "countryId": ${contryId}
}
  • 创建工具类
public class FreeMarkerUtils {
    public static String getDate(String filepath, Map<Object,Object> mode)
            throws IOException, TemplateException {
        StringWriter writer = new StringWriter();

        // 创建配置类
        Configuration cfg = new Configuration(Configuration.getVersion());
        // 设置模板加载机制:
        // 1、类加载机制加载模板
        cfg.setClassForTemplateLoading(FreeMarkerUtils.class,"/freemarker");
        // 2-1、目录路径加载模板
//        cfg.setDirectoryForTemplateLoading(new File("/freemarker"));
        // 2-2、目录路径加载模板
//        String classpath = FreeMarkerUtils.class.getResource("/").getPath();
//        cfg.setDirectoryForTemplateLoading(new File(classpath +"/freemarker"));
        // 设置字符集
        cfg.setDefaultEncoding("UTF-8");

        // 加载模板
        Template template = cfg.getTemplate(filepath);
        // 静态化内容:
        // 1.
        template.process(mode,writer);
        // 2.
        return writer.toString();
    }
}
  • 测试
@Test
public void testFreeMarkerToJson(){
    String filePath = "testFm.ftl";
    Map<Object, Object> mode = new HashMap<>();
    mode.put("cityId","1001");
    mode.put("cityName","深圳");
    mode.put("cky2","800");
    mode.put("contryId","000001");
    try {
        String date = FreeMarkerUtils.getDate(filePath, mode);
        System.out.println(date);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TemplateException e) {
        e.printStackTrace();
    }
}

二、一次性收集模板(xml)

  • 创建xml解析类
@XmlRootElement(name = "mappingItem")
public class MappingItem {
    private String solutionName;
    private String templateName;

    @XmlAttribute(name = "solutionName")
    public String getSolutionName() {
        return solutionName;
    }

    public void setSolutionName(String solutionName) {
        this.solutionName = solutionName;
    }

    @XmlAttribute(name = "templationName")
    public String getTemplateName() {
        return templateName;
    }

    public void setTemplateName(String templateName) {
        this.templateName = templateName;
    }
}

//----------

@XmlRootElement(name = "templateMapping")
public class TemplateMapping {
    private List<MappingItem> mappingItemList;

    @XmlElement(name = "mappingItem")
    public List<MappingItem> getMappingItemList() {
        return mappingItemList;
    }

    public void setMappingItemList(List<MappingItem> mappingItemList) {
        this.mappingItemList = mappingItemList;
    }
}

  • 创建工具类
public class FreeMarkerUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(FreeMarkerUtils.class);

    private static Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);

    static {
        try {
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setClassForTemplateLoading(FreeMarkerUtils.class,"/freemarker_template");

        } catch (Exception ex){
            LOGGER.error("FreeMaerkerUtils error." + ex.getMessage(), ex);
        }

    }

    public FreeMarkerUtils() { }

    public static String processData(Map<String,Object> model, String templateName){
        String result = "";
        try (StringWriter out = new StringWriter()){
            Locale locale = LocaleContextHolder.getLocale();
            Template template = cfg.getTemplate(templateName, locale);
            template.process(model, out);
            result = out.toString();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
        return result;
    }


     // 1、通过xml配置文件获取模板
    public static Map<String, String> getTemplateConfig(){
        Map<String, String> templateConfig = new HashMap<>();
        try (InputStream inputStream = FreeMarkerUtils.class.getResourceAsStream(
                "/freemarker_template/freemarker_template_mapping.xml")){
            // 读取jar包内置文件
            JAXBContext context = JAXBContext.newInstance(TemplateMapping.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();

            XMLInputFactory xif = XMLInputFactory.newFactory();
            xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,false);
            xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            XMLStreamReader xsr = xif.createXMLStreamReader(inputStream);

            TemplateMapping templateMapping = (TemplateMapping) unmarshaller.unmarshal(xsr);

            List<MappingItem> mappingItemList = templateMapping.getMappingItemList();
            for (MappingItem mappingItem : mappingItemList) {
                templateConfig.put(mappingItem.getSolutionName(), mappingItem.getTemplateName());
            }
        } catch (Exception ex){
            LOGGER.error(ex.getMessage());
        }
        return templateConfig;
    }

    // 2、通过路径获取模板
    private Map<String, String> templateFiles = new HashMap<>();

    @Value("${template.base-template-path:/freemarker_template}")
    public String baceTemplatePath;

    @Value("${template.base-template-path:.ftl}")
    public String templateSuffix;

    @PostConstruct
    protected void initTemplateFile(){
        try {
            URL resource = FreeMarkerUtils.class.getResource(baceTemplatePath);
            String rootPath = resource.getPath();
            File rootFile = new File(rootPath);
            File[] listFiles = rootFile.listFiles();
            Objects.requireNonNull(listFiles, String.format(Locale.ROOT, "[%s] no template file.", baceTemplatePath));
            for (File file : listFiles) {
                if (!Objects.isNull(file) && file.isFile() && file.getName().endsWith(templateSuffix)){
                    String filePath = file.getPath();
                    String fileName = file.getName();
                    templateFiles.put(
                            fileName.substring(0,fileName.lastIndexOf(".")), filePath.substring(rootPath.length())
                    );
                    LOGGER.info("get template path:" + filePath);
                }
            }
        } catch (Exception exception){
            LOGGER.error("initTemplateFile faild.", exception.getMessage());
        }
    }

    public Map<String, String> getTemplateFiles() {
        return templateFiles;
    }
  • 创建目录及定义模板
// 【/freemarker_template/freemarker_template_mapping.xml】
<?xml version="1.0" encoding="utf-8" ?>
<templateMapping>
    <mappingItem solutionName="test1" templationName="test1.ftl"></mappingItem>
    <mappingItem solutionName="test2" templationName="test2.ftl"></mappingItem>
    <mappingItem solutionName="test3" templationName="test3.ftl"></mappingItem>
</templateMapping>
name: ${name}
  • 创建测试接口
@ResponseBody
@RequestMapping(value = "/testTemplate", method = RequestMethod.GET)
public String freemarker(Map<String, Object> map, String name){
    Map<String, String> templateConfig = FreeMarkerUtils.getTemplateConfig();
    Map<String, Object> mode = new HashMap<>();
    mode.put("name", name);

    String templateName = templateConfig.get("test1");
    String result = FreeMarkerUtils.processData(mode, templateName);
    return result;
}

版权声明:本文为qq_41617261原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。