,,,Thymeleaf的出现是为了取代JSP,虽然JSP存在了很长时间,并在Java Web开发中无处不在,但是它也存在一些缺陷:
1, JSP最明显的问题在于它看起来像HTML或XML,但它其实上并不是。大多数的JSP模板都是采用HTML的形式,但是又掺杂上了各种JSP标签库的标签,使其变得很混乱。
2, JSP规范是与Servlet规范紧密耦合的。这意味着它只能用在基于Servlet的Web应用之中JSP模板不能作为通用的模板(如格式化电子邮件),也不能用于非Servlet的Web应用。
,,,相较于JSP来说,Thymeleaf很好的解决了这些缺点:
1, Thymeleaf模板是原生的,不依赖于标签库。它能在接受原始HTML的地方进行编辑和渲染。
2,因为它没有与Servlet规范耦合,因此Thymeleaf模板能够进入JSP所无法涉足的领域。这意味着Thymeleaf模板与JSP不同,它能够按照原始的方式进行编辑甚至渲染,而不必经过任何类型的处理器。当然,我们需要Thymeleaf来处理模板并渲染得到最终期望的输出。即便如此,如果没有任何特殊的处理,home也能够加载到网页浏览器中,并且看上去与完整渲染的效果很类似。
,,,弹簧引导不建议使用JSP开发网络。
,,,SpringBoot对Thymeleaf模板引擎的支持也很简单:
,,,1,pom.xml
& lt; dependency> & lt; groupId> org.springframework.boot & lt; artifactId> spring-boot-starter-thymeleaf & lt;/dependency>
这时候,SpringBoot对Thymeleaf模板的支持就完成了,我们就能在网上开发中使用Thymeleaf模板了,简单吧?
之前的文章有提到SpringBoot的关键是“约定俗成“。既然我们选择了这么简单的配置,那么在开发中就要遵守SpringBoot对Thymeleaf约定俗成的方案,最重要的一点就是模板文件放在模板目录下,即模板解析器前缀是/模板/后缀是html。
,,,2,application.yml
,,,如果不想要所谓约定俗成的方案,想进行一些自定义的配置呢?且看下方:
春天: thymeleaf: 前缀:类路径://模板 后缀:. html servlet: 内容类型:text/html 启用:真 utf - 8编码: 模式:HTML5 缓存:假
,,,3,WebConfig.java
,,,如果上面的配置还不能达到你的要求,你想要更细化对Thymeleaf的控制,包括配置视图解析器,模板解析器以及模板引擎这些,那么请看下面的方案!
/* * * 1,ThymeleafViewResolver接收逻辑视图名称将它解析为视图 * 2,SpringTemplateEngine会在春天中启用Thymeleaf引擎,用来解析模板,并基于这些模板渲染结果 * 3、TemplateResolver会最终定位和查找模板。 */@ configuration 公开课WebConfig {/* * *配置Thymeleaf视图解析器——将逻辑视图名称解析为Thymeleaf模板视图 * * @param springTemplateEngine模板引擎 * @return */@ bean 公共ViewResolver ViewResolver (SpringTemplateEngine SpringTemplateEngine) { ThymeleafViewResolver解析器=new ThymeleafViewResolver (); resolver.setTemplateEngine (springTemplateEngine); 返回解析器; }/* * *模板引擎,处理模板并渲染结果 * * @param templateResolver模板解析器 * @return */@ bean 公共SpringTemplateEngine SpringTemplateEngine (ITemplateResolver templateResolver) { SpringTemplateEngine SpringTemplateEngine=new SpringTemplateEngine (); springTemplateEngine.setTemplateResolver (templateResolver); 返回springTemplateEngine; }/* * *模板解析器——加载Thymeleaf模板 * * @return */@ bean 公共ITemplateResolver templateResolver () { SpringResourceTemplateResolver templateResolver=new SpringResourceTemplateResolver (); templateResolver.setPrefix(“类路径:/模板/?; templateResolver.setSuffix (" . html "); templateResolver.setTemplateMode (TemplateMode.HTML); templateResolver.setCacheable(假); templateResolver.setTemplateMode (“HTML5”); 返回templateResolver; } }
,,,做好了上面的配置后,让我们来看看如何在SpringBoot中使用Thymeleaf模板吧:
,,,1、模板文件-/模板/user/list.html
& lt; !DOCTYPE html> & lt; html xmlns: th=" http://www.thymeleaf.org "比; & lt; head> & lt;元charset=" utf - 8 "/比; & lt; title>插入标题hereSpringBoot中的Thymeleaf模板