在web大行其道的今天,有了接口之后最好的展示方式就是用页面。而Spring Boot中对于模板页有良好的支持。下面我们来介绍Spring Boot推荐的模板 thymeleaf。
- 首先在pom.xml中加入依赖:
org.springframework.boot spring-boot-starter-thymeleaf
需要注意,为了让thymeleaf识别一个模板,你必须使用下面的html头标签:
...
- 引入javascript
首先我们在resources目录下新建templates文件夹和static文件夹。
关于这两个文件夹,在Spring Boot中,静态资源默认是访问resources下的static文件夹,动态html资源默认是访问resourcess目录下的templates。当然这两个默认路径可以再application.yml中进行配置,一般我们都使用默认路径。由于我们需要的是一个由Spring Boot生成的动态模板页,因此在templates下新建demo1.html。
由于动态模板页需要先经过后台接口,然后才返回一个html页面到前端,因此在controller文件夹下新建ThymeleafController.java。
@Controllerpublic class ThymeleafController { @GetMapping("/thymeleaf") public String testMapper() { return "demo1"; }}
注意我们使用了@Controller而不是@RestController。具体的区别请查看Spring Boot从入门到精通-注解详解。
写了一个路径为/thymeleaf的接口,该接口直接返回了一个值为我们需要返回的html的名字的字符串。
目录结构如下:
目录结构
- 引入普通文本:th:text
hello world!
- 引入变量: ${变量名}
- 变量名由后台传递给前端,因此需要修改接口。
@GetMapping(value = "thymeleaf") public String articleInfo(Model model) { model.addAttribute("data