SpringBoot+Thymeleaf基于HTML5现代模板引擎的方法
开始使用1.引入依赖SpringBoot默认提供了Thymeleaf的Starter,只需简单引入依赖即可。org.springframework.bootspring-boot-starter-thymeleaf目前默认版本是2.1,如果想升级版本到3.0,可以这样修改。3.0.7.RELEASE2.0.0为了方便开发,项目案例采用了热部署工具dev-tools,这样我们在修改页面之后,IDEA会自动加载,从而达到实现热更新的效果。org.springframework.bootspring-boot-
开始使用
1.引入依赖
SpringBoot默认提供了Thymeleaf的Starter,只需简单引入依赖即可。
org.springframework.boot spring-boot-starter-thymeleaf
目前默认版本是2.1,如果想升级版本到3.0,可以这样修改。
3.0.7.RELEASE 2.0.0
为了方便开发,项目案例采用了热部署工具dev-tools ,这样我们在修改页面之后,IDEA会自动加载,从而达到实现热更新的效果。
org.springframework.boot spring-boot-devtools runtime
注:由于IDEA默认关闭了热部署,需要做一些设置才能使其生效。解决方法:首先按住Ctrl+Shift+Alt+/ 然后进入 Registry ,然后勾选compiler.automake.allow.when.app.running 即可。另外,Build->Compiler 也要勾选上Build Project automatically .
2. 添加相关配置
Thymeleaf默认开启了页面缓存,在开发的时候,应该关闭缓存。此外,通常我们还会指定页面的存放路径。(默认是classpath:/templates/)
application.yml 配置如下: spring: thymeleaf: cache: false #关闭缓存 prefix: classpath:/views/ #添加路径前缀
3.编写HTML
编写Thymeleaf和书写HTML5页面没有什么不同,最大的转变就是使用拓展属性(th:xx)去跟服务端进行数据交互,保留原始页面风格,也是Thymeleaf的推崇的风格。例如下面这个简单的案例,启动项目,我们发现页面跳转的是简书的连接,这一点也验证了Thymeleaf覆盖原生页面数据的极佳能力。
页面代码:
Thymeleaf 欢迎使用Thymeleaf!!
戳我有惊喜
后端代码:
@Controller
public class UserController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("info", "user/list");
return "index";
}
@GetMapping("/user")
public String hehe(Model model) {
model.addAttribute("user", new User(UUID.randomUUID().toString(), "yizhiwazi", "20170928"));
return "user";
}
@GetMapping("/user/list")
public String userlist(Model model) {
List userList = new ArrayList<>();
userList.add(new User(UUID.randomUUID().toString(), "yizhiwazi", "20170928"));
userList.add(new User(UUID.randomUUID().toString(), "kumamon", "123456"));
userList.add(new User(UUID.randomUUID().toString(), "admin", "admin"));
model.addAttribute("userList", userList);
return "userList";
}
} 现在我们尝试回填一个表单,展示单个用户信息。
接下来,我们进入一个更复杂的案例,例如展示一个用户列表信息,不需要编写新的标签,就可以完成对批量用户的遍历。
用户列表
用户姓名: 登录密码:
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















