springboot使用freemarker模板

首先先下载依赖:

<!--freeMarker模板-->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-freemarker -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
   <version>2.1.3.RELEASE</version>
</dependency>

 

然后配置freemarker的配置信息:

#freeMarker配置
#request属性是否可以覆盖controller中model的同名项
spring.freemarker.allow-request-override=false

#httpsession的属性是否可以覆盖controller中的model的同名项
spring.freemarker.allow-session-override=false

#是否开启缓存
spring.freemarker.cache=false

#模板文件编码
spring.freemarker.charset=UTF-8

#检查模板文件位置
spring.freemarker.check-template-location=true

#content-type的值
spring.freemarker.content-type=text/html

#是否将HHttpServletRequest中的属性添加到model中
spring.freemarker.expose-request-attributes=false

#是否将HHttpSession中的属性添加到model中
spring.freemarker.expose-session-attributes=false

#模板文件后缀
spring.freemarker.suffix=.ftl

#模板文件位置
spring.freemarker.template-loader-path=classpath:/templates/

然后在resources下新建一个templates目录,默认路径

 

下面通过一个简单的例子来看一下:

@Controller
public class BookController {
// @Autowired
// Book book;

   @GetMapping("/seeBook")
   public ModelAndView seeBook() {
      System.out.println("调用seeBook方法");
      Book b1 = new Book();
      b1.setName("三国演义");
      b1.setAuthor("罗贯中");
      b1.setPrice(25f);
      b1.setTimes("2019-8-9");
      Book b2 = new Book();
      b2.setName("红楼梦");
      b2.setAuthor("曹雪芹");
      b2.setPrice(27f);
      b2.setTimes("2019-9-9");

      List<Book> books = new ArrayList<>();
      books.add(b1);
      books.add(b2);
//    返回视图
      ModelAndView mv = new ModelAndView();
//    mv.addObject("books",books);
//    mv.setViewName("books");

      mv.addObject("booksfree",books);
      mv.setViewName("booksfree");
      return mv;
   }
}

 

新建模板文件:freebooks.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书列表</title>
</head>
<body>
<table border="1">
    <tr>
        <td>图书名称</td>
        <td>图书作者</td>
        <td>图书价格</td>
        <td>出版时间</td>
    </tr>

<#if booksfree ??&&(booksfree?size>0)>
    <#list booksfree as book>
        <tr>
            <td>${book.name}</td>
            <td>${book.author}</td>
            <td>${book.price}</td>
            <td>${book.times}</td>
        </tr>
    </#list>
</#if>
</table>
</body>
</html>

 

那么我们看一下结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值