spring-boot之(6) web freemarker
前面说过传统前后端未分离的项目,基本上都是基于动态页面的,而且spring-boot是支持模板引擎的,
- FreeMarker
- Groovy
- Thymeleaf
- Mustache
值得说的是JSP尽量避免使用,因为spring-boot使用的是内嵌的Web容器,内嵌的Web容器在使用jsp的时候有限制。
- 加入FreeMarker依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freeMarker</artifactId> <version>1.3.5.RELEASE</version> </dependency>
请确保freeMarker正确被加载,否则会出默认视图找不到
- 编写Controller层代码
@Controller public class PageController { @RequestMapping("/good") public String good(Map<String, Object> attribute){ attribute.put("username", "hello freemarker"); return "good"; } }
- 编写freemarker页面代码
动态模板文件good.ftl放在spring-boot默认目录src/main/resources/templates
<html> <head> <title>goods</title> </head> <body> <div> freemarker template - ${username} </div> </body> </html>
- 访问http://localhost/good
freemarker template - hello freemarker
- 在application.yml加上freemarker的配置
spring: freemarker: allow-request-override: false cache: true charset: UTF-8 check-template-location: true content-type: text/html enabled: true expose-request-attributes: false expose-session-attributes: false expose-spring-macro-helpers: false prefer-file-system-access: true suffix: .ftl template-loader-path: classpath:/templates/ #template-loader-path指定模板目录
- 另:默认错误页面
页面是html页面的话,找到静态资源根路径(假设为/public),然后在目录下面添加/error目录,然后添加404.html,结构目录如下
src/
+- main/
+- java/
| + <source code>
+- resources/
+- public/
+- error/
| +- 404.html
+- <other public assets>
如果页面是像freemarker页面的话,比如5xx。就在模板根路径增加/error目录,然后新增5xx.ftl,结构目录如下
src/
+- main/
+- java/
| + <source code>
+- resources/
+- templates/
+- error/
| +- 5xx.ftl
+- <other templates>
- 参考资料
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-developing-web-applications

浙公网安备 33010602011771号