SpringBoot+thymeleaf

  1. springboot项目默认是不允许直接访问template下的文件的,想要访问template下的页面,我们需要配置视图解析器,要设置好视图去展示页面,可以用一个模板来接受后台返回的数据如thymeleaf、freemarker、jsp,SpringBoot官方是不推荐使用jsp的,推荐使用thymeleaf作为模板语言。
  2. 解决在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>

  1. 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
  1. 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";
    }
}
  1. 在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>
  1. 页面访问localhost:8080/home 就可以访问到templates下对应的页面了,关于thymeleaf的语法,这里不做详细介绍,可以去他们的官网看看。
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值