SpringBoot入门之Thymeleaf的使用

在.net的MVC3 或更高版本等支持 Razor 的框架里使用cshtml,Razor是一种简单的编程语法,用于在网页中嵌入服务器端代码.在使用springboot开发mvc时也有与.net类似的视图引擎.
Spring Boot提供了大量的模板引擎,包含了FreeMarker,Groovy,Thymeleaf,Velocity和Mustache,Spring Boot中推荐使用Thymeleaf作为模板引擎,因为Thymeleaf提供了完美的Spring MVC的支持。Thymeleaf是一个java类库,它是一个xml/xhtml/html5的模板引擎,可以作为MVC的Web应用的View层。Thymeleaf还提供了额外的模块与Spring MVC集成,所以我们可以使用Thymeleaf完全替代JSP。
一、Thymeleaf配置
Thymeleaf有哪些属性可以配置呢,我们可以在org.springframework.boot.autoconfigure.thymeleaf下的ThymeleafProperties.class找到属性,springboot约定大于配置,所以在ThymeleafProperties.class中也都有默认值,如果我们想改变默认值可以在application.properties设置。这里用的都是它的默认值。默认路径在templates下,文件是html文件。

 

二、项目引入Thymeleaf

这里还是在上一springboot博客的例子基础上进行修改,这里需要在pom.xml引入Thymeleaf,这里要注意一下,由于用的是spring5,如果引入的Thymeleaf版本不正确就可能会报错,而且不同的spring引入Thymeleaf的artifactId也不一样。

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.9.RELEASE</version>
        </dependency>

同时如果在html页面使用还需要在html增加一行

<html xmlns:th="http://www.thymeleaf.org">

三、测试

这里创建了一个Controller和一个html.Thymeleaf的属性都是用的默认的属性值,如果需要改变可以在resources/application.properties下更改,前缀名是spring.thymeleaf。

复制代码
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


//@RestController
@Controller
public class HelloController {

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello(Model model) {
        model.addAttribute("name", "Cuiyw");
        return "hello";
    }
}
复制代码
复制代码
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello!, ' + ${name} + '!'" ></p>
</body>
</html>
复制代码

posted @   社会主义接班人  阅读(7534)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示