本文为Spring Boot2.1系列的第十一篇,代码可以从github下载 https://github.com/yinww/demo-springboot2.git
freemarker是1999年就发布了第一版的老牌的模板引擎,具有很多优点,也被springboot支持,freemarker的相关内容大家可以参考其他资料。
本文对freemarker的模板资源和静态资源做外部化配置进行介绍。
一、创建工程demo011
pom.xml的内容为
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yinww</groupId>
<artifactId>demo-springboot2</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>demo011</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
二、Java类
主类
package com.yinww.demo.springboot2.demo011;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Demo011Application {
public static void main(String[] args) {
SpringApplication.run(Demo011Application.class, args);
}
}
控制类
package com.yinww.demo.springboot2.demo011.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class TestController {
@RequestMapping(value={"", "/", "index.html"})
public ModelAndView index() {
ModelAndView model = new ModelAndView();
model.addObject("hi", "欢迎学习springboot 和 freemarker");
model.setViewName("index");
return model;
}
}
三、配置
application.properties 添加配置
spring.freemarker.cache=false
spring.freemarker.suffix=.html
spring.freemarker.templateLoaderPath=file:E:/tmp/templates/
spring.resources.static-locations=file:E:/tmp/static/
四、html和css
E:/tmp/templates/ 路径下 index.html文件内容:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="welcome.css">
<title>hello</title>
</head>
<body>
<div class="welcome">${hi}</div>
</body>
</html>
E:/tmp/static/ 路径下welcom.css 文件内容:
.welcome{color: #F00}
五、运行程序
启动程序后,访问 http://localhost:8080/ 页面显示如下

至此实现了对freemarker的模板和静态资源的外部化配置,freemarker的其他参数配置相对比较简单,这里不做介绍。
本文内容到此结束,更多内容可关注公众号:

本文是Spring Boot2.1系列第十一篇,介绍了使用Spring Boot2实现Freemarker的模板资源和静态资源的外部化配置。包括创建工程、编写Java类、进行配置、设置html和css文件,最后运行程序实现配置,代码可从github下载。
825

被折叠的 条评论
为什么被折叠?



