springboot使用thymeleaf语言

本文介绍如何在Spring Boot项目中配置并使用Thymeleaf模板引擎,包括添加Maven依赖、设置模板配置及实现数据展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先先加入maven依赖:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
   <version>2.0.4.RELEASE</version>
</dependency>

然后在resources下新建一个templates目录,默认路径

然后在配置文件中写入thymeleaf 的配置信息:

#thymeleaf配置
#是否开启缓存,默认为true
spring.thymeleaf.cache=true

#检查模板是否存在,默认为true
spring.thymeleaf.check-template=true

#检查模板位置是否存在,默认为true
spring.thymeleaf.check-template-location=true

#模板文件编码
spring.thymeleaf.encoding=UTF-8

#模板文件位置
spring.thymeleaf.prefix=classpath:/templates/

#content-type配置
spring.thymeleaf.servlet.content-type=text/html

#模板文件后缀
spring.thymeleaf.suffix=.html

下面我们来做一个测试:

@Controller
public class BookController {
// @Autowired
// Book book;

   @GetMapping("/seeBook")
   public ModelAndView seeBook() {
      System.out.println("调用seeBook方法");
      Book b1 = new Book();
      b1.setName("三国演义");
      b1.setAuthor("罗贯中");
      b1.setPrice(25f);
      b1.setTimes("2019-8-9");
      Book b2 = new Book();
      b2.setName("红楼梦");
      b2.setAuthor("曹雪芹");
      b2.setPrice(27f);
      b2.setTimes("2019-9-9");

      List<Book> books = new ArrayList<>();
      books.add(b1);
      books.add(b2);
//    返回视图
      ModelAndView mv = new ModelAndView();
      mv.addObject("books",books);
      mv.setViewName("books");

//    mv.addObject("booksfree",books);
//    mv.setViewName("booksfree");
      return mv;
   }
}

然后我们在页面上将数据展示出来:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>图书列表</title>
</head>
<body>
<table border="1">
    <tr>
        <td>图书名称</td>
        <td>图书作者</td>
        <td>图书价格</td>
        <td>出版时间</td>
    </tr>
    <tr th:each="book:${books}">
        <td th:text="${book.name}"></td>
        <td th:text="${book.author}"></td>
        <td th:text="${book.price}"></td>
        <td th:text="${book.times}"></td>
    </tr>
</table>
</body>
</html>

如果出现404错误那么就检查一下依赖是否完成下载或者依赖版本是否正确,那么我们来看一下结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值