SpringBoot中FreeMarker创建

1、创建SpringBoot项目时,勾选freemarker依赖(web,dev)
2、Controller中向model中存放数据

package com.ziv.springbootbygralde.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ziv.springbootbygralde.entity.UserEntity;

@Controller
@RequestMapping("/temp")
public class FreeMarkerController {

    private static final Logger log = LoggerFactory.getLogger(FreeMarkerController.class);

    @RequestMapping("/show")
    public String show(Model model) {
        
        model.addAttribute("str", "Hello Spring Boot freemarker");
        UserEntity userEntity = new UserEntity();
        userEntity.setId(100);
        userEntity.setName("zhong ziv");
        model.addAttribute("stu", userEntity);

        List<UserEntity> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            UserEntity usertemp = new UserEntity();
            usertemp.setId(i);
            usertemp.setName("user" + i);
            list.add(usertemp);
        }
        model.addAttribute("user", list);

        log.info(model.toString());
        return "show";
    }
    
    
    @RequestMapping("/Demofreemarker")
    public String freemarker(Model model) {
        
        model.addAttribute("str", "Hello Spring Boot freemarker");
        ///返回string必须和templates中的文件名称一致,否则报错
        return "freemarker";
    }
}

3、freemarker模板默认在templates/*.ftl可以在配置文件中改变设置

#freemarker configuration
#freemarker *.ftl
spring.freemarker.suffix=.html
#freemarker文件的目录,默认目录为templates下面的文件,web文件目录下的文件
spring.freemarker.template-loader-path=classpath:/web

4、freemarker模板上设置

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="/js/jquery-3.4.1.min.js"></script>
</head>
<body>
    <h3>show:${str}</h3>
    <hr>
    <h3>用户</h3>
    <!-- ??判断stu是否存在,是否为null -->
    <#if stu??>
    <!-- id==1001才进行显示 -->
    <#if stu.id ==1001>
    编码:${stu.id}<br>
    名称:${stu.name}<br>
    <#else>
    学生信息不为1001
    </#if>
    <#else>
    没有学生信息
    </#if>
    <hr>
    <h3>遍历学生</h3>
    <#list user as u>
    编码:${u.id}<br>
    名称:${u.name}<br>
    <hr>
    </#list>
    <button id="btn" >点击</button>
    <script type="text/javascript">
    $("#btn").click(function(){
        alert("click");
    })
    </script>
</body>
</html>
View Code

 

posted @ 2019-06-05 16:01  Ziv_zhong  阅读(266)  评论(0编辑  收藏  举报