在以前的示例中,咱们都是经过@RestController来处理请求,因此返回的内容为json对象。咱们如今须要实现更复杂的页面显示,就须要用到模板引擎来帮我实现了。
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合以下规则:html
/static /public /resources /META-INF/resources
例如:咱们在src/main/resources/目录下建立static,并在该位置放置一个图片文件A.jpg。启动程序后,访问http://localhost:8080/A.jpg。如能显示图片,则配置成功。web
在动态HTML实现上Spring Boot依然能够完美胜任,而且提供了多种模板引擎的默认配置支持,因此在推荐的模板引擎下,咱们能够很快的上手开发动态网站。spring
Spring Boot提供了默认配置的模板引擎主要有如下几种:json
Thymeleaf FreeMarker Velocity Groovy Mustache
在这里咱们发现没有咱们曾经最熟悉的JSP,那是由于JSP没法实现Spring Boot的多种特性,若是非要使用JSP,也是能够经过配置进行实现的。后面咱们再说。缓存
Thymeleaf是一种简单且容易上手的模板引擎,咱们如今就选择它来进行具体的介绍吧!app
咱们根据上一篇文章新建一个项目,在选择依赖的时候须要选择Web和Thymeleaf便可。spring-boot
打开pom.xml文件咱们能够看到引入的依赖。测试
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
在Spring Boot中使用Thymeleaf,只须要引入上面的依赖,并在默认的模板路径src/main/resources/templates下编写模板文件便可完成。网站
下面咱们来简单的写一个示例:编码
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>测试页面</title> </head> <body> <h1 th:text="${newWorld}">Hello World</h1> </body> </html>
注意:若是想要使用模板引擎的话,就须要在页面引用thymeleaf语法空间。就是 xmlns:th="http://www.thymeleaf.org",thymeleaf的语法就是th:xxxx=“数据”,具体能够看官方说明文档。
@RequestMapping("/index") public String index(ModelMap map){ map.addAttribute("newWorld","WELCOME TO NEW WORLD!!!"); return "index"; }
运行项目,输入项目地址再次查看页面显示内容,内容被替换了。
在application.yml中能够配置thymeleaf模板解析器属性
# THYMELEAF (ThymeleafAutoConfiguration) #开启模板缓存(默认值:true) spring.thymeleaf.cache=true #Check that the template exists before rendering it. spring.thymeleaf.check-template=true #检查模板位置是否正确(默认值:true) spring.thymeleaf.check-template-location=true #Content-Type的值(默认值:text/html) spring.thymeleaf.content-type=text/html #开启MVC Thymeleaf视图解析(默认值:true) spring.thymeleaf.enabled=true #模板编码 spring.thymeleaf.encoding=UTF-8 #要被排除在解析以外的视图名称列表,用逗号分隔 spring.thymeleaf.excluded-view-names= #要运用于模板之上的模板模式。另见StandardTemplate-ModeHandlers(默认值:HTML5) spring.thymeleaf.mode=HTML5 #在构建URL时添加到视图名称前的前缀(默认值:classpath:/templates/) spring.thymeleaf.prefix=classpath:/templates/ #在构建URL时添加到视图名称后的后缀(默认值:.html) spring.thymeleaf.suffix=.html #Thymeleaf模板解析器在解析器链中的顺序。默认状况下,它排第一位。顺序从1开始,只有在定义了额外的TemplateResolver Bean时才须要设置这个属性。 spring.thymeleaf.template-resolver-order= #可解析的视图名称列表,用逗号分隔 spring.thymeleaf.view-names=