千家信息网

SpringBoot中如何使用Thymeleaf操作

发表于:2024-10-23 作者:千家信息网编辑
千家信息网最后更新 2024年10月23日,这篇"SpringBoot中如何使用Thymeleaf操作"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面
千家信息网最后更新 2024年10月23日SpringBoot中如何使用Thymeleaf操作

这篇"SpringBoot中如何使用Thymeleaf操作"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇"SpringBoot中如何使用Thymeleaf操作"文章吧。

前言

Thymeleaf是一个适用于Web和独立环境的现代服务器端Java模板引擎。

Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板 - 可以在浏览器中正确显示的HTML,也可以用作静态原型,从而在开发团队中实现更强大的协作。

通过Spring Framework模块,与您喜欢的工具的大量集成,以及插入您自己的功能的能力,Thymeleaf是现代HTML5 JVM Web开发的理想选择

Thymeleaf与Velocity或FreeMarker等其他模板引擎相比如何?

Velocity 和 FreeMarker 都是非常棒的软件,但是它们处理模板问题的原理与Thymeleaf 完全不同。

Thymeleaf 非常强调自然模板化——允许模板成为工作原型,而其他两个模板不允许这样做——它的语法试图(可以说)更干净,更符合当前 web开发的趋势。另外,从架构的角度来看,Velocity 和 FreeMarker 都是顺序文本处理器,而 Thymeleaf 是基于标记解析技术的。这允许 Thymeleaf 利用特定于基于标记的环境的有趣特性,特别是web。

SpringBoot使用Thymeleaf 操作步骤

第一步是引入Thymeleaf starter依赖,具体代码如下:

                    org.springframework.boot            spring-boot-starter-thymeleaf        

第二步是在 application.properties 添加 Thymeleaf 相关配置,具体配置如下:

server.port=8090server.servlet.context-path=/sbe#关闭 Thymeleaf 的缓存开发过程中无需重启spring.thymeleaf.cache = false#设置thymeleaf页面的编码spring.thymeleaf.encoding=UTF-8spring.thymeleaf.mode=HTML5#设置thymeleaf页面的后缀spring.thymeleaf.suffix=.html#设置thymeleaf页面的存储路径spring.thymeleaf.prefix=classpath:/templates/

第三步是编写访问 Thymeleaf 页面 Controller。

@Controller@RequestMapping("/hello")public class ThymeleafHelloWrodController {        @RequestMapping("/thymeleaf")    public String helloThymeleaf(Model model){        model.addAttribute("hello","hello Thymeleaf!");        return "hello/index";    }}

Thymeleaf 页面代码如下:

Insert title here    

hello

测试

在游览器输入访问 Thymeleaf 页面的 Controller 的 URL:http://localhost:8090/sbe/hello/thymeleaf 进行测试,测试结果如下:

以上就是关于"SpringBoot中如何使用Thymeleaf操作"这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注行业资讯频道。

0