Springbooot整合thymeleaf开发

本文介绍了Thymeleaf作为服务器端Java模板引擎的用途,如何在IDEA中配置以优化开发体验,以及如何通过Maven集成到SpringBoot项目中。展示了如何处理模板和集合遍历的基本示例,最后提到了访问测试以验证配置和功能。

一、Thymeleaf简介


Thymeleaf 是一个服务器端 Java 模板引擎,能够处理 HTML、XML、CSS、JAVASCRIPT 等模板文件。Thymeleaf 模板可以直接当作静态原型来使用,它主要目标是为开发者的开发工作流程带来优雅的自然模板,也是 Java 服务器端 HTML5 开发的理想选择。

二、准备工作-IDEA设置


在开始使用ThymeLeaf作为模板引擎进行页面开发之前,我们有必要对IDEA进行一些设置。这些设置帮助IDEA更好的识别ThymeLeaf语法,增强我们的开发体验。

  • 安装ThymeLeaf插件,并使其生效(在绝大多数的IDEA版本该插件都是默认安装并生效的)

  • 去掉变量表达式识别检查,会造成变量红色下划线,影响开发体验

三、集成


使用Maven坐标将thymeleaf引入到项目中

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

对thymeleaf模板进行配置

spring:
  thymeleaf:
    cache:false # 启用缓存:建议生产开启
    check-template-location:true # 检查模版是否存在
    enabled:true # 是否启用
    encoding: UTF-8 # 模版编码
    excluded-view-names: # 应该从解析中排除的视图名称列表(用逗号分隔)
    mode: HTML5 # 模版模式
    prefix: classpath:/templates/ # 模版存放路径
    suffix:.html # 模版后缀

四、Hello ThymeLeaf


例子完成之后,项目代码结构如下:

查询一个articles文章列表,并返回模板名称,由Spring根据名称找到模板进行页面渲染

import com.zimug.boot.launch.model.ArticleVO;
import com.zimug.boot.launch.service.ArticleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/template")
public class TemplateController{

    @Resource
    ArticleService articleService;

    @GetMapping("/thymeleaf")
    public String index(Model model){

        List<ArticleVO> articles = articleService.getAll();

        model.addAttribute("articles", articles);//模版名称,实际的目录为:resources/templates/thymeleaftemp.htmlreturn"thymeleaftemp";}}

新建thymeleaf模板页面:thymeleaftemp.html。

  • 注意:th:each是thymelaef,其核心功能是集合遍历

<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Title</title><link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css"></head><body><div class="container"><table class="table"><tr><td>作者</td><td>教程名称</td><td>内容</td></tr><tr th:each="item : ${articles}"><td th:text="${item.author}"></td><td th:text="${item.title}"></td><td th:text="${item.content}"></td></tr></table></div><script src="/webjars/jquery/jquery.min.js "></script><script src="/webjars/bootstrap/js/bootstrap.min.js"></script></body></html>

五、访问测试


访问测试地址: http://localhost:8888/template/thymeleaf

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

枫叶(接毕设)QQ:3042127848

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值