← Back to list

thymeleaf (1) 环境配置

Published on: | Views: 88

引入

简单博客页面,使用vue开发,发现不好做SEO, 打算用thymeleaf再写下。

导入相当简单:

    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

在resource目录下面的templates目录中放一个简单主页:

<body>
 <h1>Hello thymeleaf</h1>
</body>

然后写个controller转发请求:

    @GetMapping(value = "/index")
    public String index() {
        return "index";
    }

点击运行,访问http://localhost:8080/index, 就能看到页面了。

热更新

现在修改一下index.html,发现界面无变化,刷新也不行,总不能每次修改都重新编译吧? thymeleaf确实没有热更新机制, 但配置好了也只要刷新页面就可以看到更改了。 先关闭缓存:(application.properties)

spring.thymeleaf.cache=false

这时候修改,按下Ctrl+Shift+F9,再刷新页面就可以了。 更进一步,可以修改好自动更新代码,配置如下: image.png 设置 on frame deactivation 为 update resources 就可以了,这时候修改资源文件后,切换到其他界面就会自动更新资源。

一个简单的渲染

在model中放入属性,在页面中可以通过${属性名}直接获取到。

    @GetMapping(value = "/index")
    public String index(Model model) {
        model.addAttribute("message","hello world!");
        return "index";
    }
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh">
<body>
    <p th:text="${message}"></p>
</body>
</html>

thymeleaf内置对像

  • ctx: the context object.

  • vars: the context variables.

  • locale: the context locale.

  • request: (only in Web Contexts) the HttpServletRequest object.

  • response: (only in Web Contexts) the HttpServletResponse object.

  • session: (only in Web Contexts) the HttpSession object.

  • servletContext: (only in Web Contexts) the ServletContext object.

    像上面这个例子,也就可以写成:
<p th:text="${#request.getAttribute('message')}"></p>

还有一些扩展对象,可以查阅官方文档: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html