微服式务分布云构架Spring Boot模板引擎-集成Thymeleaf

一、集成Thymeleaf
了解springcloud架构可以加求求:三五三六二四七二五九
  第一步:引入jar包(thymeleaf对应的starter):

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

第二步:配置thymeleaf:

spring:
  thymeleaf:
    prefix: classpath:/templates/
    check-template-location: true
    cache: false
    suffix: .html
    encoding: UTF-8
    content-type: text/html
    mode: HTML5

prefix:指定模板所在的目录

check-tempate-location: 检查模板路径是否存在

cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。

encoding&content-type:这个大家应该比较熟悉了,与Servlet中设置输出对应属性效果一致。

mode:这个还是参考官网的说明吧,并且这个是2.X与3.0不同,本文自动引入的包是2.15。

第三步 编写thymeleaf模板文件:

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta content="text/html;charset=UTF-8"/>
</head>
<body>
<h6>Thymeleaf 模板引擎</h6>
<table border="1" bgcolor="#f0ffff">
    <thead>
    <tr>
        <th>序号</th>
        <th>标题</th>
        <th>摘要</th>
        <th>创建时间</th>
    </tr>
    </thead>
    <tbody th:each="article : ${list}">
    <tr>
        <td th:text="${article.id}"></td>
        <td th:text="${article.title}"></td>
        <td th:text="${article.summary}"></td>
        <td th:text="${article.createTime}"></td>
    </tr>
    </tbody>
</table>
</body>
</html>

大家可以看到,thymeleaf还是比较简单的,并且最大的特点就是的标签是作为HTML元素的属性存在的,也就是说,该页面是可以直接通过浏览器来预览的,只是没有数据而已,这个很方便大家进行调试。
 第四步 配置Controller:

@Controller
@RequestMapping("/article")
public class ArticleController {
 
    @Autowired
    private ArticleService articleService;
 
    @RequestMapping("/articleList.html")
    public String getArticleList(Model model, String title, @RequestParam(defaultValue = "10") Integer pageSize,
                                 @RequestParam(defaultValue = "1") Integer pageNum) {
        int offset = (pageNum - 1) * pageSize;
        List<Article> list = articleService.getArticles(title, 1L, offset, pageSize);
        model.addAttribute("list", list);
        return "article/articleList";
    }
}

注意,这里用的注解是@Controller,而不是@RestController,因为@RestController会自动将返回结果转为字符串。
资源来源

发布了93 篇原创文章 · 获赞 93 · 访问量 4284

猜你喜欢

转载自blog.csdn.net/weixin_45821812/article/details/104496416