Spring Boot中添加Thymeleaf模板

Spring Boot中添加Thymeleaf模板

前面我们讲解了Spring Boot项目的创建、Spring Boot结构信息,自动配置功能等,那么Springboot创建出来,我们最终是要做web开发的,所以我们这章讲解如何用SpringBoot做web开发。

一. Web开发方式

Spring boot提供了一套完整的web开发流程,从前端到后台,再到数据库,定时任务,消息队列等都可以支持.一般利用Spring框架开发一个Web应用有两种方式:

1. 使用Spring boot自带的模板

Spring Boot 提供了spring-boot-starter-web来为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及SpringMVC的依赖,用起来很方便。另外,我们还要用到模板引擎,用来显示视图页面,springboot支持的模板引擎很多,包括Thymeleaf, FreeMarker, Groovy, Mustache, Velocity, JSP等,

之前Java第七模块讲解Thymeleaf时已经讲解过jsp现在不建议使用,我们这里用Thymeleaf来做模板。

2. 前后端分离(后面章节里讲)

这种方式前端开发和后端开发完全分离,可以由前后端两个团队分开同步开发,只需要协商好接口就行,前端负责开发页面并调用后端接口展示数据,后端负责提供Restful风格的接口.

二 用Spring Boot创建带有Thymeleaf模板的web项目

Thymeleaf相关知识看Java第七模块。

这里直接讲解Springboot中怎么整合Themeleaf模板。

我们先在springboot中使用Thymeleaf,看看简化了哪些步骤,再来分析为什么会简化。

1.用Spring Initializr 方式 创建springboot项目

Spring Boot中添加Thymeleaf模板_第1张图片

Spring Boot中添加Thymeleaf模板_第2张图片

Spring Boot中添加Thymeleaf模板_第3张图片

选择web依赖

Spring Boot中添加Thymeleaf模板_第4张图片

选择Thymeleaf依赖

Spring Boot中添加Thymeleaf模板_第5张图片

Spring Boot中添加Thymeleaf模板_第6张图片

Spring Boot中添加Thymeleaf模板_第7张图片

2.创建出来的项目结构

Spring Boot中添加Thymeleaf模板_第8张图片

3.创建html模板页面

html标签中添加     xmlns:th="http://www.thymeleaf.org"

Spring Boot中添加Thymeleaf模板_第9张图片

4.创建控制层页面

Spring Boot中添加Thymeleaf模板_第10张图片

5.运行

Spring Boot中添加Thymeleaf模板_第11张图片

Spring Boot中添加Thymeleaf模板_第12张图片

6.在哪里做的自动配置

通过上面的操作,我们会发现我们不需要配置视图的前缀和后缀了,这是因为系统已经帮我自动配置了。

自动配置信息在:

Spring Boot中添加Thymeleaf模板_第13张图片

Spring Boot中添加Thymeleaf模板_第14张图片

Spring Boot中添加Thymeleaf模板_第15张图片

可以看到 默认配置的前缀为templates文件夹

后缀为.html

所以我们只需要把html页面建在templates文件夹下就可以。

7.如何修改自动配置

比如将后缀名改为.htm

先找到后缀名配置名称:

Spring Boot中添加Thymeleaf模板_第16张图片

然后在配置文件application.properties中添加

 spring.thymeleaf.suffix=.htm   

Spring Boot中添加Thymeleaf模板_第17张图片

添加后缀名为.htm的模板文件

Spring Boot中添加Thymeleaf模板_第18张图片

运行:

Spring Boot中添加Thymeleaf模板_第19张图片

Spring Boot中添加Thymeleaf模板_第20张图片

你可能感兴趣的:(Java基础知识,spring,boot,java,spring)