全部
常见问题
产品动态
精选推荐

Spring Boot 2.x基础教程:使用 Thymeleaf开发Web页面

管理 管理 编辑 删除

接下来,我们就来具体讲讲在Spring Boot应用中,如何使用Thymeleaf模板引擎开发Web页面类的应用。

#静态资源访问

在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:

  • /static
  • /public
  • /resources
  • /META-INF/resources

举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。

#渲染Web页面

在之前的示例中,我们都是通过@RestController来处理请求,所以返回的内容为json对象。那么如果需要渲染html页面的时候,要如何实现呢?

#模板引擎

在动态HTML实现上Spring Boot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。

Spring Boot提供了自动化配置模块的模板引擎主要有以下几种:

  • Thymeleaf
  • FreeMarker
  • Groovy

当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。

补充:Spring Boot从一开始就建议使用模板引擎,避免使用JSP。同时,随着Spring Boot版本的迭代,逐步的淘汰了一些较为古老的模板引擎。

#Thymeleaf

Thymeleaf是本文我们将具体介绍使用的模板引擎。它是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。

Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。

示例模板:

<table>
  <thead>
    <tr>
      <th th:text="#{msgs.headers.name}">Name</td>
      <th th:text="#{msgs.headers.price}">Price</td>
    </tr>
  </thead>
  <tbody>
    <tr th:each="prod : ${allProducts}">
      <td th:text="${prod.name}">Oranges</td>
      <td th:text="${#numbers.formatDecimal(prod.price,1,2)}">0.99</td>
    </tr>
  </tbody>
</table>

可以看到Thymeleaf主要以属性的方式加入到html标签中,浏览器在解析html时,当检查到没有的属性时候会忽略,所以Thymeleaf的模板可以通过浏览器直接打开展现,这样非常有利于前后端的分离。

#动手试一下

第一步:新建一个Spring Boot应用,在pom.xml中加入所需的模板引擎模块,比如使用thymeleaf的话,只需要引入下面依赖:

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

第二步:创建一个Spring MVC的传统Controller,用来处理根路径的请求,将解决渲染到index页面上,具体实现如下

@Controller
public class HelloController {

    @GetMapping("/")
    public String index(ModelMap map) {
        map.addAttribute("host", "https://blog.didispace.com");
        return "index";
    }

}

简要说明:

  • 在渲染到index页面的时候,通过ModelMap,往页面中增加一个host参数,其值为https://blog.didispace.com
  • return的值index代表了要使用的模板页面名称,默认情况下,它将对应到src/main/resources/templates/目录下的index.html模板页面

第三步:根据上一步要映射的模板,去模板路径src/main/resources/templates下新建模板文件index.html,内容如下:


<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>

在该页面的body中,包含了一个带有Thymeleaf属性的h1标签,该便签内容将绑定host参数的值。

由于Thymeleaf通过属性绑定的特性。该模板页面同其他模板引擎不同,直接通过浏览器打开html页面,它是可以正常运作的,将会直接展现Hello World标题。这有利于开发页面的时候可以在非启动环境下验证应前端样式的正确性。

如果启动程序后,访问http://localhost:8080/,上面页面就会展示Controller中host的值:https://blog.didispace.com,做到了不破坏HTML自身内容的数据逻辑分离。

更多Thymeleaf的页面语法,可以访问Thymeleaf的官方文档来深入学习使用。

#Thymeleaf的配置参数

如有需要修改默认配置的时候,只需复制下面要修改的属性到application.properties中,并修改成需要的值:


# Enable template caching.
spring.thymeleaf.cache=true 
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true 
# Content-Type value.
spring.thymeleaf.content-type=text/html 
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true 
# Template encoding.
spring.thymeleaf.encoding=UTF-8 
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.excluded-view-names= 
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5 
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/ 
# Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html  spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

举几个我们常用的配置内容:

Q:不想每次修改页面都重启

A:修改spring.thymeleaf.cache参数,设置为false

Q:不想使用template目录存放模板文件

A:修改spring.thymeleaf.prefix参数,设置为你想放置模板文件的目录

Q:不想使用index作为模板文件的扩展名

A:修改spring.thymeleaf.suffix参数,设置为你想用的扩展名

Q:HTML5的严格校验很烦人

A:修改spring.thymeleaf.mode参数,设置为LEGACYHTML5

更多本系列免费教程连载「点击进入汇总目录」

#代码示例

本文的相关例子可以查看下面仓库中的chapter4-1目录:

请登录后查看

CRMEB 最后编辑于2025-02-27 14:48:27

快捷回复
回复
回复
回复({{post_count}}) {{!is_user ? '我的回复' :'全部回复'}}
排序 默认正序 回复倒序 点赞倒序

{{item.user_info.nickname ? item.user_info.nickname : item.user_name}} LV.{{ item.user_info.bbs_level }}

作者 管理员 企业

{{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest == 1? '取消推荐': '推荐'}}
{{item.is_suggest == 1? '取消推荐': '推荐'}}
沙发 板凳 地板 {{item.floor}}#
{{item.user_info.title || '暂无简介'}}
附件

{{itemf.name}}

{{item.created_at}}  {{item.ip_address}}
{{item.like_count}}
{{item.showReply ? '取消回复' : '回复'}}
删除
回复
回复

{{itemc.user_info.nickname}}

{{itemc.user_name}}

回复 {{itemc.comment_user_info.nickname}}

附件

{{itemf.name}}

{{itemc.created_at}}
{{itemc.like_count}}
{{itemc.showReply ? '取消回复' : '回复'}}
删除
回复
回复
查看更多
243
{{like_count}}
{{collect_count}}
添加回复 ({{post_count}})

相关推荐

快速安全登录

使用微信扫码登录
{{item.label}} 加精
{{item.label}} {{item.label}} 板块推荐 常见问题 产品动态 精选推荐 首页头条 首页动态 首页推荐
取 消 确 定
回复
回复
问题:
问题自动获取的帖子内容,不准确时需要手动修改. [获取答案]
答案:
提交
bug 需求 取 消 确 定

微信登录/注册

切换手机号登录

{{ bind_phone ? '绑定手机' : '手机登录'}}

{{codeText}}
切换微信登录/注册
暂不绑定
CRMEB客服

CRMEB咨询热线 咨询热线

400-8888-794

微信扫码咨询

CRMEB开源商城下载 源码下载 CRMEB帮助文档 帮助文档
返回顶部 返回顶部
CRMEB客服