- springboot项目默认是不允许直接访问template下的文件的,想要访问template下的页面,我们需要配置视图解析器,要设置好视图去展示页面,可以用一个模板来接受后台返回的数据如thymeleaf、freemarker、jsp,SpringBoot官方是不推荐使用jsp的,推荐使用thymeleaf作为模板语言。
- 解决在spring中使用thymeleaf的时候,会对html进行严格的语法校验
在application.properties中添加:spring.thymeleaf.mode=LEGACYHTML5
在pom.xml中添加
#解决在spring中使用thymeleaf的时候,会对html进行严格的语法校验
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.21</version>
</dependency>
<!-- 引入thymeleaf模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- application.properties的thymeleaf配置
spring.profiles.active=dev
#解决在spring中使用thymeleaf的时候,会对html进行严格的语法校验
spring.thymeleaf.mode=LEGACYHTML5
#thymeleaf配置
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#缓存设置为false, 这样修改之后马上生效,便于调试
# 开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
- controller层的代码,这里我从数据库查了一个list集合数据testService.testService(),使用Model把这个list集合数据放进去,前端就可以通过thymeleaf语法去遍历这个集合,Model里面可以放字符串、对象、集合都可以。
@Controller
public class MyController {
@Autowired
private TestService testService;
@GetMapping(value = "home")
//1
public String goHome(Model model) {
model.addAttribute("list",testService.testService());
return "hello";
}
}
- 在templates下新建一个HTML页面,代码如下。
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
<meta charset="UTF-8">
<title>主页</title>
</head>
<style>
tr th,td{
text-align: center;
border:1px solid black;
}
</style>
<body>
<h3>测试thymeleaf取值</h3>
<table>
<tr>
<th>ID</th>
<th>airline</th>
<th>office</th>
<th>flightNumber</th>
</tr>
<tr th:each="entity:${list}">
<td th:text="${entity.id}"></td>
<td th:text="${entity.airline}"></td>
<td th:text="${entity.office}"></td>
<td th:text="${entity.flightNumber}"></td>
</tr>
</table>
</body>
</html>
- 页面访问localhost:8080/home 就可以访问到templates下对应的页面了,关于thymeleaf的语法,这里不做详细介绍,可以去他们的官网看看。