Thymeleaf 是Java服务端的模板引擎,与传统的JSP不同,前者可以使用浏览器直接打开,因为可以忽略掉拓展属性,相当于打开原生页面,给前端人员也带来一定的便利。如果你已经厌倦了JSP+JSTL的组合,Thymeleaf或许是个不错的选择!
一、目标使用thymeleaf视图模板,并且于SpringBoot进行整合。
二、实现首先创建一个SpringBoot项目,添加如下依赖
org.springframework.boot spring-boot-starterorg.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-thymeleaf
添加完依赖以后,就需要编写对应的Controller跟view了
在resource目录下新建templates文件夹并且在该目录下新建文件index.html
Title 你好
在src/main/java/com/yukong/chapter目录下新建IndexController
@Controllerpublic class IndexController { @GetMapping("/hello") public String hello(@RequestParam(defaultValue = "world", required = false) String name, Model model) {
model.addAttribute("name", name); return "index";
}
}注意这里使用的是@Controller
然后在src/resource/application.yml配置一下thymeleaf相关配置
server: port: 8989 spring: thymeleaf: # 配置视图路径前缀 prefix: classpath:/templates/ # 配置视图路径后缀 suffix: .html mode: html # 关闭缓存 修改视图 刷新浏览器就显示 开发阶段务必关闭缓存 (=false) cache: false
启动Chapter21Application.java并且访问http://localhost:8989/hello
结果如图:
image.png
再次访问http://localhost:8989/hello?name=yukong
结果如图
image.png
作者:余空啊
链接:https://www.jianshu.com/p/66d1be96ea1e



