在pom.xml中引入freemarker依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
修改yml,引入freemarker
spring:
freemarker:
request-context-attribute: req #req访问request
suffix: .html #后缀名
content-type: text/html
enabled: true
cache: false #缓存配置
# templates-loader-path: classpath:/templates/ #模板加载路径 按需配置
charset: UTF-8 #编码格式
settings:
number_format: '0.##' #数字格式化,无小数点
在resources下新建templates目录,把模板文件放入其中。
说明:模板文件后缀是html,因为spring.freemarker.suffix=html,如果需要是ftl后缀,请修改yml文件。
css\js\image 等文件可以放在resource\static目录下,html引入时可以直接用src = “./js/aaa.js”
创建Controller,统一处理.html请求
@Controller
@RequestMapping("/")
public class CommonPageController {
@RequestMapping("{page}.html")
public ModelAndView pageHtml(@PathVariable("page") String page) {
return new ModelAndView(page);
}
}
对于需要传值的模板,单独建Controller处理。
@RequestMapping("myPage.html")
public ModelAndView myPage() {
ModelAndView mv = new ModelAndView("myPage");
mv.addObject("key","value");
return mv;
}
HTML中接收参数
<html>
<body>
<h1>${key}</h1>
</body>
</html>