在距离发表上一篇博文的时间整整一个月的今天,趁着放假更一篇,证明我还存在这个世界。
对于一个学习Java的童鞋,怎么能忘了学习SpringBoot这个框架呢!前段时间在学习的时候添加一个JSP页面却死活找不到页面,无奈换了Thymeleaf,官方橘子君也是推介的这个模板引擎,它完全可以替代JSP。
下面请跟上我的脚步,开车了:
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
application.propertiesde 的文件中配置Thymeleaf
详情可以看这里Spring-Boot配置文件thymeleaf模板配置项
spring.thymeleaf.cache=false //关闭模版缓存
spring.thymeleaf.encoding=UTF-8 //模版编码方式
spring.thymeleaf.check-template-location=true //检查模板位置是否存在
//SpringBoot中默认的路径为/templates/
spring.thymeleaf.prefix = classpath:/templates/ //在构建URL时预先查看名称的前缀
spring.thymeleaf.suffix = .html //构建URL时附加查看名称的后缀
创建templates文件
在resources中New Directory,名称必须为templates!之后在其中创建自己的HTML文件就好。
文件结构如下:
Controller
//千万不能使用RestController注解,不然是无法返回界面的,只会返回Return中的内容。
@Controller
public class IndexController {
@GetMapping("/index")
public String index() {
return "index";
}
@GetMapping("/")
public String hello() {
return "hello";
}
}
HTML界面
在上面创建的templates文件夹中创建Controller中Return内容相对应的界面,例如我Controller中返回了一个index和一个hello,那么我就需要创建这两个界面,可以根据GetMapping的路径来访问不同的界面。