SpringBoot中整合使用Freemarker

场景

springboot不建议使用jsp,使用模板引擎,比如thymeleaf,velocity,freemarker。

项目搭建专栏:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/column/info/35688

实现

首先在项目中引入freemarker相关依赖。

<!-- springboot整合freemark -->
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-freemarker</artifactId>
  </dependency>

springboot会默认在resource下的templates下去寻找模板。

新建show.ftl

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
 ${name}
</body>
</html>

在Controller包下新建TestFreeMarker .java

package com.example.demo.controller;

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

@Controller
public class TestFreeMarker {
 
 @RequestMapping("/freemarker")
 public String show(Model model) {
  model.addAttribute("name","霸道流氓气质");
  return "show";
 }
}

运行代码后效果

如果要想配置freemarker的一些其他配置,在application.properties中添加

#springboot整合freemarker
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
#设置模板格式
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#设置文件后缀
spring.freemarker.suffix=.ftl
#设置配置文件位置
spring.freemarker.template-loader-path=classpath:/templates

源码下载

https://download.csdn.net/download/badao_liumang_qizhi/11089061

猜你喜欢

转载自blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/89074931