1、引言
关于springboot项目的创建可以看下面这篇文章,这里不进行叙述,可以参考之前的文章SpringBoot入门:使用IDEA和Eclipse构建第一个SpringBoot项目。
2、Freemarker模板
首先在pom文件中引入freemarker的依赖,代码如下:
<!-- Spring Boot Freemarker 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> 复制代码
然后在com.example.demo文件夹下新建一个controller文件夹,新建FreemarkerController类,代码如下:
package com.example.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class FreemarkerController { @RequestMapping(value="/freemarker",method = RequestMethod.GET) public String freemarker(Model model) { model.addAttribute("name", "李青"); model.addAttribute("age", 22); model.addAttribute("id", 223); return "freemarker"; } } 复制代码
在application.yml文件中配置freemarker,修改的yml文件,新建默认的是application文件,yml配置如下:
#yml和property文件功能一样都是配置设置,比如数据库、端口号等等,但是yml的 #结构是树状结构比较明朗,而且相同的内容因为是树状展示不用重复写 #但是如果项目中两个文件同时存在则优先加载property,yml的配置无效 #注意,eclipse中yml文件用tab键进行缩进,会报错。 spring freemarker: # prefix: classpath:/templates/ suffix: .ftl content-type: text/html template-loader-path: classpath:/templates 复制代码
在templates文件夹下新建freemarker.ftl文件,代码如下:
<!DOCTYPE html> <html lang="en"> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <body> 姓名:${name}<br><br> 年龄:${age}<br><br> 编号:${id}<br><br> </body> </html> 复制代码
启动项在浏览器地址栏输入,http://localhost:8080/freemarker页面结果如下:
freemarker页面模板创建完成!
3、Thymeleaf模板
同样在pom文件中引入thymeleaf依赖,代码如下:
<!--引入thymeleaf的依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> 复制代码
在controller文件夹下新建ThymeleafController类,代码如下
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 ThymeleafController { @RequestMapping("/thymeleaf") public String test(Model model) { model.addAttribute("name", "李青"); model.addAttribute("age", 22); model.addAttribute("id", 223); return "thymeleaf"; } } 复制代码
在application.yml文件中配置thymeleaf,代码如下:
spring: thymeleaf: prefix: classpath:/templates/ suffix: .html mode: HTML5 encoding: UTF-8 cache: false content-type: text/html 复制代码
然后在templates文件夹下新建thymeleaf.html页面文件,代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> 姓名:<input type="text" th:value="${name}"><br/> 年龄:<input type="text" th:value="${age}"><br/> 编号:<input type="text" th:value="${id}"><br/> </body> </html> 复制代码
启动项目,在浏览器地址栏输入,http://localhost:8080/thymeleaf,页面结果如下:
thymeleaf页面模板创建完成!
总结
本文主要介绍了springboot如何使用freearker和thymeleaf模板高效的创建页面。