SpringBoot Thymeleaf 模板引擎渲染视图

本贴最后更新于 2512 天前,其中的信息可能已经沧海桑田

静态资源访问

在我们开发 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
Velocity
Groovy
Mustache
Spring Boot 建议使用这些模板引擎,避免使用 JSP,若一定要使用 JSP 将无法实现 Spring Boot 的多种特性,具体可见后文:支持 JSP 的配置

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

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 中使用 Thymeleaf,只需要引入下面依赖,并在默认的模板路径 src/main/resources/templates 下编写模板文件即可完成。


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

在完成配置之后,举一个简单的例子,在快速入门工程的基础上,举一个简单的示例来通过 Thymeleaf 渲染一个页面。


	@Controller
	public class HelloController {
	    @RequestMapping("/")
	    public String index(ModelMap map) {
	        // 加入一个属性,用来在模板中读取
	        map.addAttribute("host", "http://blog.didispace.com");
	        // return模板文件的名称,对应src/main/resources/templates/index.html
	        return "index";  
	    }
	}

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

如上页面,直接打开 html 页面展现 Hello World,但是启动程序后,访问 http://localhost:8080/,则是展示 Controller 中 host 的值:http://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= # Or
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    941 引用 • 1458 回帖 • 153 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...