SpringBoot(四) Web开发 --- Thymeleaf、JSP

 Spring Boot提供了spring-boot-starter-web为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及Spring MVC的依赖。

模板引擎

Spring Boot支持多种模版引擎包括:

  • FreeMarker
  • Groovy
  • Thymeleaf(官方推荐)
  • Mustache

JSP技术Spring Boot官方是不推荐的,原因有三:

  1. tomcat只支持war的打包方式,不支持可执行的jar。
  2. Jetty 嵌套的容器不支持jsp
  3. Undertow
  4. 创建自定义error.jsp页面不会覆盖错误处理的默认视图,而应该使用自定义错误页面

Thymeleaf引擎模板

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。它的功能特性如下:

  • Spring MVC中@Controller中的方法可以直接返回模板名称,接下来Thymeleaf模板引擎会自动进行渲染
  • 模板中的表达式支持Spring表达式语言(Spring EL)
  • 表单支持,并兼容Spring MVC的数据绑定与验证机制
  • 国际化支持

Spring官方也推荐使用Thymeleaf,所以本篇代码整合就使用Thymeleaf来整合。

使用Thymeleaf

1.加入依赖

复制代码
 1 <dependency>  2     <groupId>org.springframework.boot</groupId>  3     <artifactId>spring-boot-starter-thymeleaf</artifactId>2.1.6</dependency>  4   5 <properties>  6         <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>  7         <!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->  8         <!-- thymeleaf2   layout1-->  9         <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version> 10   </properties>
复制代码

 

 

只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

2.导入thymeleaf的名称空间

复制代码
<html 
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信