静态资源访问css
在咱们开发Web应用的时候,须要引用大量的js、css、图片等静态资源。html
默认配置spring
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合以下规则:json
/static /public /resources /META-INF/resources 举例:咱们能够在src/main/resources/目录下建立static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。后端
渲染Web页面浏览器
在以前的示例中,咱们都是经过@RestController来处理请求,因此返回的内容为json对象。那么若是须要渲染html页面的时候,要如何实现呢?app
模板引擎spring-boot
在动态HTML实现上Spring Boot依然能够完美胜任,而且提供了多种模板引擎的默认配置支持,因此在推荐的模板引擎下,咱们能够很快的上手开发动态网站。网站
Spring Boot提供了默认配置的模板引擎主要有如下几种:ui
Thymeleaf FreeMarker Velocity Groovy Mustache Spring Boot建议使用这些模板引擎,避免使用JSP,若必定要使用JSP将没法实现Spring Boot的多种特性,具体可见后文:支持JSP的配置
当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。固然也能够修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。
Thymeleaf
Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández建立,该做者仍是Java加密库Jasypt的做者。
Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可使用Thymeleaf来彻底代替JSP或其余模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板建立方式,所以也能够用做静态建模。你可使用它建立通过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中便可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。
示例模板:
Name | Price |
---|---|
Oranges | 0.99 |
在Spring Boot中使用Thymeleaf,只须要引入下面依赖,并在默认的模板路径src/main/resources/templates下编写模板文件便可完成。
org.springframework.boot spring-boot-starter-thymeleaf 在完成配置以后,举一个简单的例子,在快速入门工程的基础上,举一个简单的示例来经过Thymeleaf渲染一个页面。@Controller public class HelloController {
@RequestMapping("/")
public String index(ModelMap map) {
// 加入一个属性,用来在模板中读取
map.addAttribute("host", "http://blog.didispace.com");
// return模板文件的名称,对应src/main/resources/templates/index.html
return "index";
}
复制代码
}
更多Thymeleaf的页面语法,还请访问Thymeleaf的官方文档查询使用。
Thymeleaf的默认参数配置
若有须要修改默认配置的时候,只需复制下面要修改的属性到application.properties中,并修改为须要的值,如修改模板文件的扩展名,修改默认的模板路径等。
spring.thymeleaf.cache=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.excluded-view-names=
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved. 支持JSP的配置
Spring Boot并不建议使用,但若是必定要使用,能够参考此工程做为脚手架:JSP支持