SpringMVC 中的视图如何使用 Thymeleaf

简介: SpringMVC 中的视图如何使用 Thymeleaf

SpringMVC 中的视图如何使用 Thymeleaf


SpringMVC 是一个基于 Java 的 Web 框架,它是 Spring 框架的一部分,提供了一系列的组件和工具,帮助开发人员构建 Web 应用程序。其中,视图是 Spring MVC 中的核心组件之一,它负责将模型数据渲染成 HTML 页面并返回给客户端。Thymeleaf 是一种流行的模板引擎,它可以方便地将模型数据渲染成 HTML 页面。本文将介绍 SpringMVC 中的视图如何使用 Thymeleaf,并提供示例代码。


image.png


Thymeleaf 简介


Thymeleaf 是一个流行的模板引擎,它可以方便地将模型数据渲染成 HTML 页面。Thymeleaf 的模板语法与 HTML 语法非常相似,可以直接在 HTML 页面中嵌入 Thymeleaf 表达式。Thymeleaf 还提供了一系列的标准标签和属性,可以对 HTML 页面进行动态渲染。


下面是一个简单的 Thymeleaf 表达式示例:


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Example</title>
</head>
<body>
    <h1 th:text="${message}">Hello, World!</h1>
</body>
</html>

在上面的代码中,我们使用了 Thymeleaf 的 th:text 属性来渲染模型数据。这个属性会将 ${message} 表达式替换为模型中的 message 变量。


Thymeleaf 集成到 SpringMVC 中


Thymeleaf 可以与 SpringMVC 集成,用于渲染视图。下面我们来看一下如何将 Thymeleaf 集成到 SpringMVC 中。


步骤一:添加 Thymeleaf 依赖

在 pom.xml 文件中添加 Thymeleaf 的依赖:

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

骤二:配置 Thymeleaf 模板解析器

在 SpringMVC 的配置文件中,配置 Thymeleaf 模板解析器:


@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        return engine;
    }
    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }
}

在上面的代码中,我们创建了一个 SpringResourceTemplateResolver 对象,指定了 Thymeleaf 模板文件的位置和后缀名。然后,我们创建了一个 SpringTemplateEngine 对象,并将模板解析器设置为其属性。最后,我们创建了一个 ThymeleafViewResolver 对象,并将模板引擎设置为其属性。


步骤三:使用 Thymeleaf 视图

在控制器中,我们可以使用 Thymeleaf 视图来渲染模型数据。例如:

@Controller
public class HelloWorldController {
    @GetMapping("/hello")
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello, World!");
        return "hello";
    }
}

在上面的代码中,我们使用了 Model 对象来添加模型数据,并将 Thymeleaf 视图名称设置为 “hello”。Thymeleaf 视图名称的格式为 “文件名:后缀”,其中文件名是在 Thymeleaf 模板文件夹中的相对路径,后缀是 Thymeleaf 模板文件的后缀名。


步骤四:创建 Thymeleaf 模板文件

最后,我们需要在 Thymeleaf 模板文件夹中创建一个对应的模板文件。例如,在上面的示例中,我们需要在 “/WEB-INF/views/” 目录下创建一个名为 “hello.html” 的文件,文件内容如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Example</title>
</head>
<body>
    <h1 th:text="${message}">Hello, World!</h1>
</body>
</html>

在上面的代码中,我们使用了 Thymeleaf 的 th:text 属性来渲染模型数据。这个属性会将 ${message} 表达式替换为模型中的 message 变量。


完整示例代码


下面是一个完整的使用 Thymeleaf 的 SpringMVC 示例代码:


WebConfig.java


@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        return engine;
    }
    @Bean
    public ViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }
}

HelloWorldController.java


@Controller
public class HelloWorldController {
    @GetMapping("/hello")
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello, World!");
        return "hello";
    }
}

hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Example</title>
</head>
<body>
    <h1 th:text="${message}">Hello, World!</h1>
</body>
</html>

总结


本文介绍了如何在 SpringMVC 中使用 Thymeleaf 来渲染视图。我们首先简要介绍了 Thymeleaf 的基本语法和特点,然后详细介绍了如何将 Thymeleaf 集成到 SpringMVC 中,并提供了示例代码。使用 Thymeleaf 可以方便地将模型数据渲染成 HTML 页面,并且 Thymeleaf 的语法与 HTML 的语法非常相似,易于上手。


相关文章
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8072 2
|
11天前
|
域名解析 人工智能 Linux
|
21天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
18705 64
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10102 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
5天前
|
人工智能 安全 网络安全
|
10天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1519 5
|
9天前
|
云安全 数据采集 人工智能
|
16天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2673 8
|
9天前
|
Web App开发 缓存 安全
巨魔商店 TrollStore 安装教程(2026):免电脑在线安装与全机型安装器矩阵_iOS巨魔安装
巨魔商店(TrollStore)是iOS 14–17.0(特定版本)的永久签名工具,无需越狱,利用CoreTrust漏洞实现IPA签名长期有效,彻底告别7天重签。支持免电脑在线安装(TrollHelperOTA),适配多机型/系统组合,开源免费,安全可控。(239字)
2226 0