温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Thymeleaf怎么在SpringBoot中使用

发布时间:2021-05-19 16:23:09 来源:亿速云 阅读:139 作者:Leah 栏目:编程语言

这期内容当中小编将会给大家带来有关Thymeleaf怎么在SpringBoot中使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

1.引入依赖:

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

2.application.properties

#是否开启缓存,开发时可设置为false,默认为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

3.创建实体类和controller类

public class Book {
  private Integer id;
  private String name;
  private String author;
  //省略getter/setter
}
@Controller
public class BookController {
  @GetMapping("/books")
  public ModelAndView books() {
    List<Book> books = new ArrayList<>();
    Book b1 = new Book();
    b1.setId(1);
    b1.setAuthor("罗贯中");
    b1.setName("三国演义");
    Book b2 = new Book();
    b2.setId(2);
    b2.setAuthor("曹雪芹");
    b2.setName("红楼梦");
    books.add(b1);
    books.add(b2);
    ModelAndView mv = new ModelAndView();
    mv.addObject("books", books);
    mv.setViewName("books");
    return mv;
  }
}

4.html文件:

<!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>
  </tr>
  <tr th:each="book:${books}">
    <td th:text="${book.id}"></td>
    <td th:text="${book.name}"></td>
    <td th:text="${book.author}"></td>
  </tr>
</table>
</body>
</html>

5.结果:

Thymeleaf怎么在SpringBoot中使用

springboot是什么

springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。

上述就是小编为大家分享的Thymeleaf怎么在SpringBoot中使用了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI