SpringBoot | 第二十九章:SpringBoot集成Thymeleaf模板引擎渲染web视图

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Thinkingcao/article/details/87783571

一、新建SpringBoot项目springboot-thymeleaf,引入pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.thinkingcao</groupId>
    <artifactId>springboot-thymeleaf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-thymeleaf</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

二、静态资源访问

在我们开发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>

六、 在完成配置之后,举一个简单的例子

     1. 新建编辑控制层代码HelloController,在request添加了name属性,

       HelloController.java

package com.thinkingcao.springbootthymeleaf.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(HttpServletRequest request, @RequestParam(value = "name", defaultValue = "默认值springboot-thymeleaf") String name) {
        request.setAttribute("name", name);
        return "index";
    }
}

    2.新建编辑模板文件,在resources文件夹下的templates目录,用于存放HTML等模板文件,在这新增hello.html,添加如下代码

      index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--<p th:text="'hello, ' + ${name} + '!'"/>-->
<h1 th:text="${name}">Hello World</h1>
</body>
</html>

     切记:使用Thymeleaf模板引擎时,必须在html文件上方添加该行代码使用支持Thymeleaf。

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

如上页面,直接打开html页面展现Hello World,但是启动程序后,

访问http://localhost:8080/hello,则是展示Controller中name的值:默认值springboot-thymeleaf,

如果访问http://localhost:8080/hello?name=SpringBoot整合thymeleaf测试 ;那么则显示的是name的值,做到了不破坏HTML自身内容的数据逻辑分离。

3.启动项目,访问http://localhost:8080/hello,看到如下显示证明SpringBoot整合Thymeleaf成功。

Thymeleaf的默认参数配置

如有需要修改默认配置的时候,只需复制下面要修改的属性到application.properties中,并修改成需要的值,如修改模板文件的扩展名,修改默认的模板路径等。

# 是否使用缓存,开发阶段最填false,方便使用ctrl+shift+F9 进行重新编译,无需重启服务
spring.thymeleaf.cache=false
# 检查该模板是否存在
spring.thymeleaf.check-template-location=true
# 模板中内容的类型
spring.thymeleaf.content-type=text/html
# 启动 MVC 对Thymeleaf 视图的解析
spring.thymeleaf.enabled=true
# 模板的字符集
spring.thymeleaf.encoding=UTF-8
# 从解析中排除的视图名称的逗号分隔列表,没有的话就空咯
spring.thymeleaf.excluded-view-names=
# 使用的是什么类型模板
spring.thymeleaf.mode=HTML5
# 在构建URL时可以预览查看名称的前缀。就是路径在哪
spring.thymeleaf.prefix=classpath:/templates/
# 在构建URL时附加到视图名称的后缀。就是我们用rest风格,不同加文件后缀名。自己加上去
spring.thymeleaf.suffix=.html

 七、项目完整结构图

    

 八、支持JSP的配置

            SpringBoot集成JSP

 九、参考资料

          使用Thymeleaf模板引擎渲染web视图

    

猜你喜欢

转载自blog.csdn.net/Thinkingcao/article/details/87783571