在springboot中使用thymeleaf
因为jsp需要先编译,再渲染,而thymeleaf使用的html5格式,不再需要先编译再访问,而且,html格式,大部分内容更容易懂,而且当关闭缓存以后,能实时更新页面内容。
使用thymeleaf关闭缓存的方法:
新建一个controller类。
package com.example.control; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MyController { @RequestMapping("/hehe") public String hehe(Model model){ model.addAttribute("stid",1001); model.addAttribute("stname","lili"); return "show"; } }
此类的函数返回一个show的指向,所以在resources的templates中新建一个show.html,为什么是这里呢,因为,在properties里有设备。
# THYMELEAF (ThymeleafAutoConfiguration) # 开启模板缓存(默认值: true )改成false spring.thymeleaf.cache=false # 检查模板是否存在,然后再呈现 spring.thymeleaf.check-template=true # 检查模板位置是否正确(默认值 :true ) spring.thymeleaf.check-template-location=true #Content-Type 的值(默认值: text/html ) spring.thymeleaf.content-type=text/html # 开启 MVC Thymeleaf 视图解析(默认值: true ) spring.thymeleaf.enabled=true # 模板编码 spring.thymeleaf.encoding=UTF-8 # 要被排除在解析之外的视图名称列表,?逗号分隔 spring.thymeleaf.excluded-view-names= # 要运?于模板之上的模板模式。另? StandardTemplate-ModeHandlers( 默认值: HTML5) spring.thymeleaf.mode=HTML5 # 在构建 URL 时添加到视图名称前的前缀(默认值: classpath:/templates/ ) spring.thymeleaf.prefix=classpath:/templates/ # 在构建 URL 时添加到视图名称后的后缀(默认值: .html ) spring.thymeleaf.suffix=.html
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h2>编号:<em th:text="${stid}">em>h2>
<h1>名称:<em th:text="${stname}">em>h1>
<p>bbbbbbbb小小小小小小小泪水叔叔步步上小不p>
body>
html>
上面的html的名字就是show.html,然后,再修改项目设置。
然后,点击OK,就可以运行项目了,然后,不管怎么更改html里的内容,客户端页面刷新就会看到修改的内容。