springBoot提供了spring-boot-starter-web,它有嵌入式 Tomcat 以及 Spring MVC 的依赖
因为JSP在内嵌Servlet 的容器上运行有一些问题(内嵌Tomcat、Jetty不支持以 jar 包的形式运行 JSP,Undertow不支持 JSP),SpringBoot提供了大量的模板引擎,包括FreeMarker、Groovy、Thymeleaf、Velocity和Mustache,推荐使用Thymeleaf,因为它提供了完美的SpringMVC的支持。
Thymeleaf是一个 xml/xhtml/html 的模板引擎,可以作为MVC的 Web 应用的 View 层,还提供了额外的模块与Spring MVC集成,可以代替JSP:
下面的代码是一个基本的Thymeleaf模板页面,这里引入了Bootstrap(样式控制)和jQuery(DOM操作)
<!--通过下面的命名空间,将静态页面转换为动态的视图。需要动态处理的元素将使用th:作为前缀--> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta content="text/html;charset="UTF-8"/> <!-- 通过"@{}"引用Web静态资源,在JSP下是极易出错的 --> <link th:src="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet"/> <link th:src="@{bootstrap/css/bootstrap-theme.min.css}" rel="stylesheet"/> </head> <body> <!-- 通过"@{}"引用Web静态资源,在JSP下是极易出错的 --> <script th:src="@{jquery-1.10.2.min.js}" type="text/javascript"></script> <script th:src="@{bootstrap/js/bootstrap.min.js}"></script> </body> </html>通过”${}”访问model中的属性,与JSP很相似。
<div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">访问model</h3> </div> <div class="panel-body"> <!-- 使用下面的语句访问singlePerson的那么属性--> <span th:text="${singlePerson.name}"></span> </div> </div>Thymeleaf里的实现代码如下:
<!--通过th:inline添加到script标签,这样javascript代码中即可访问model中的属性--> <script th:inline="javascript"> <!--通过[[${}]]格式获得实际的值--> var single = [[${singlePerson}]]; console.log(single.name +"/"+single.age) </script>在html中获得model的值
<li class="list-group-item" th:each="person:${people}"> <span th:text="${person.name}"></span> <span th:text="${person.age}"></span> <!-- 注意格式th:onclick--> <button class="btn" th:onclick="'getName(\'' + ${person.name} + '\');'">获得名字</button> </li>在Spring MVC中需要集成模板引擎的话,需要定义ViewResolver并且在ViewResolver中定义view,如下面代码,InternalResourceViewResolver 中定义了 JstlView;
@Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/classes/views/"); viewResolver.serSuffix(".jsp"); viewResolver.setViewClass(JstlView.class); return vireResolver; }庆幸 Thymeleaf 定义好了 org.thymeleaf.spring4.view.ThymeleafView 和 org.thymeleaf.spring4.view.ThymeleafViewResolver。其中调用关系如下图所示:
上图中,与SpringMVC集成的过程在SpringBoot中通过 org.springframework.boot.autoconfigure.thymeleaf 包对 Thymeleaf 进行了自动配置。通过查看 ThymeleafProperties 源码,可在 application.properties 中,以 spring.thymeleaf 来配置 Thymeleaf。