Perfree

Perfree

Perfree

简简单单的生活,安安静静的写博客~

54 文章数
71 评论数

SpringBoot-整合Thymeleaf

perfree
2018-12-29 / 0 评论 / 1985 阅读 / 0 点赞

thymeleaf 跟 JSP 一样,就是运行之后,就得到纯 HTML了。 区别在与,不运行之前, Thymeleaf 也是 纯 html ...
所以 Thymeleaf 不需要 服务端的支持,就能够被以 html 的方式打开,这样就方便前端人员独立设计与调试, jsp 就不行了, 不启动服务器 jsp 都没法运行出结果来。
接下来将Thymeleaf和SpringBoot进行整合:

新建项目

本实例Github地址03-Thymeleaf

勾选web

勾选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>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <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-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>

其中Thymeleaf的依赖为:

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

前端控制器Controller

页面

创建hello.html

其中声明当前文件是 thymeleaf, 里面可以用th开头的属性

name

把 name 的值显示在当前 p里,用的是th开头的属性: th:text, 而取值用的是 "${name}" 这种写法叫做 ognl,额。。。什么意思呢。。。就是跟EL表达式一样吧。 这样取出来放进p 里,从而替换到 原来p 标签里的 4个字符 "name" .

用这种方式,就可以把服务端的数据,显示在当前html里了。 重要的是: 这种写法是完全合法的 html 语法,所以可以直接通过浏览器打开 hello.html,也是可以看到效果的, 只不过看到的是 "name", 而不是 服务端传过来的值 "thymeleaf"。

application.properties

#thymeleaf 配置
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#缓存设置为false, 这样修改之后马上生效,便于调试
spring.thymeleaf.cache=false

运行

文章不错,扫码支持一下吧~
上一篇 下一篇
评论
来首音乐
最新回复
光阴似箭
今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月