springboot可以通过简单的配置集成freemarker
添加maven依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.5.RELEASE</version> </parent> <artifactId>spring-freemarker</artifactId> <name>spring-freemarker</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> </dependencies> </project>
添加application.properties并添加freemarker相关配置
spring.freemarker.enabled=true
spring.freemarker.suffix=.ftl
spring.mvc.static-path-pattern=/static/**
查看其他的模板配置可以访问https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#templating-properties
添加测试类
@SpringBootApplication @Controller public class SpringFreemarkerApplication { @RequestMapping("/index") public String index() { return "index"; } public static void main(String[] args) { SpringApplication.run(SpringFreemarkerApplication.class, args); } }
创建src/main/java/resources/templates目录,添加index.ftl文件
<head> <script type="text/javascript" src="/static/index.js"></script> </head> <body onload="windowOnLoad();"> <h1>Hello World</h1> <div id="div"></div> </body>
创建src/main/java/resources/static目录,添加index.js文件
function windowOnLoad() { document.getElementById("div").innerHTML = "Hello From JS"; }
启动应用,访问http://localhost:8080/index可以看到如下内容:
说明配置成功